Skip to content

Instantly share code, notes, and snippets.

@rayworks
Last active April 12, 2017 07:49
Show Gist options
  • Save rayworks/ce933efc201ba6c5c8f001b658e26ca0 to your computer and use it in GitHub Desktop.
Save rayworks/ce933efc201ba6c5c8f001b658e26ca0 to your computer and use it in GitHub Desktop.
Scale the image based on the target view's dimension while keeping its ratio, and then make the cropped part blurred.
private void refreshAvatar(File file) {
/***
* Note: the current Fragment has been created once entering the home Activity.
* So the dimension of avatarParent is determinate already.
*/
if (file != null && file.exists()) {
avatarParent.setBackground(defaultBackground);
Glide.with(this).load(file.getAbsoluteFile())
.asBitmap()
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// origin bitmap
int bmpWidth = resource.getWidth();
int bmpHeight = resource.getHeight();
int width = avatarParent.getWidth();
int height = avatarParent.getHeight();
showBlurredBitmap(resource, bmpWidth, bmpHeight, width, height);
}
});
}
}
private void showBlurredBitmap(Bitmap resource, final int bmpWidth, final int bmpHeight, final int width, final int height) {
Observable.just(resource)
.map(bitmap -> {
// scale the image while keeping its ratio
int scaledHeight = (int) (bmpHeight * 1.0f * width / bmpWidth);
Bitmap scaledBmp = Bitmap.createScaledBitmap(bitmap, width, scaledHeight, false);
// center vertically
Bitmap dstBitmap = Bitmap.createBitmap(scaledBmp, 0, (scaledHeight - height) / 2, width, height);
// scale down bitmap first
// http://trickyandroid.com/advanced-blurring-techniques/
float scaleFactor = 8;
int radius = 20;
Bitmap overlay = Bitmap.createBitmap((int) (width * 1.0f / scaleFactor),
(int) (height * 1.0f / scaleFactor), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(overlay);
canvas.scale(1 / scaleFactor, 1 / scaleFactor);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(dstBitmap, 0, 0, paint);
Timber.i(">>> new bmp size w:%d|h:%d", dstBitmap.getWidth(), dstBitmap.getHeight());
Timber.i(">>> blurring started");
dstBitmap = FastBlurUtil.doBlur(overlay, radius, true);
Timber.i(">>> blurring end");
return dstBitmap;
})
.subscribeOn(RxSchedulerProvider.getInstance().computation())
.observeOn(RxSchedulerProvider.getInstance().ui())
.subscribe(bitmap -> {
Drawable[] drawables = new Drawable[]{
new BitmapDrawable(getResources(), bitmap), alphaDrawable};
avatarParent.setBackground(new LayerDrawable(drawables));
}, throwable -> {
Timber.e(throwable.getMessage());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment