Skip to content

Instantly share code, notes, and snippets.

@jayrambhia
Last active December 8, 2020 21:26
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jayrambhia/82e85f4bee9361dc8b9db6d0ea5e5cd5 to your computer and use it in GitHub Desktop.
Save jayrambhia/82e85f4bee9361dc8b9db6d0ea5e5cd5 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;
}
}
@maks-novikov
Copy link

how i initialize the RenderScript to create new instance of RSblurProcessor?

@arbelkilani
Copy link

@core2root

RenderScript renderScript = RenderScript.create(context);
new RSBlurProcessor(renderScript).blur(getBitmapFromView(mView), 15, 1);

@shyonge
Copy link

shyonge commented Feb 28, 2020

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@OverRide
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
getBitmapFromView(view);
}
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment