-
-
Save jilulu/93a540d8b0c4dabd12479c432b0000bc to your computer and use it in GitHub Desktop.
Android Background Blur
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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