Skip to content

Instantly share code, notes, and snippets.

@jilulu
Forked from jayrambhia/BitmapUtils.java
Created December 15, 2017 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jilulu/93a540d8b0c4dabd12479c432b0000bc to your computer and use it in GitHub Desktop.
Save jilulu/93a540d8b0c4dabd12479c432b0000bc to your computer and use it in GitHub Desktop.
Android Background Blur
public static Bitmap getBitmapFromView(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
view.draw(c);
return bitamp;
}
public class RSBlurProcessor {
private RenderScript rs;
private static final boolean IS_BLUR_SUPPORTED = Build.VERSION.SDK_INT >= 17;
private static final int MAX_RADIUS = 25;
public RSBlurProcessor(RenderScript rs) {
this.rs = rs;
}
@Nullable
public Bitmap blur(@NonNull Bitmap bitmap, float radius, int repeat) {
if (!IS_BLUR_SUPPORTED) {
return null;
}
if (radius > MAX_RADIUS) {
radius = MAX_RADIUS;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Create allocation type
Type bitmapType = new Type.Builder(rs, Element.RGBA_8888(rs))
.setX(width)
.setY(height)
.setMipmaps(false) // We are using MipmapControl.MIPMAP_NONE
.create();
// Create allocation
Allocation allocation = Allocation.createTyped(rs, bitmapType);
// Create blur script
ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
blurScript.setRadius(radius);
// Copy data to allocation
allocation.copyFrom(bitmap);
// set blur script input
blurScript.setInput(allocation);
// invoke the script to blur
blurScript.forEach(allocation);
// Repeat the blur for extra effect
for (int i=0; i<repeat; i++) {
blurScript.forEach(allocation);
}
// copy data back to the bitmap
allocation.copyTo(bitmap);
// release memory
allocation.destroy();
blurScript.destroy();
allocation = null;
blurScript = null;
return bitmap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment