Created
May 6, 2016 17:54
-
-
Save awave1/90ac124195c33657164183fedd381fe2 to your computer and use it in GitHub Desktop.
Blur drawable or bitmap on android using renderscript
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 class Blur { | |
private static final float BLUR_RADIUS = 20.5f; // 25 is maximum radius | |
// returns blur drawable if api >= 17. returns original drawable if not. | |
@Nullable | |
public static Drawable applyBlur(Drawable drawable, Context context) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { | |
Bitmap fromDrawable = drawableToBitmap(drawable); | |
int width = Math.round(fromDrawable.getWidth() * 0.8f); | |
int height = Math.round(fromDrawable.getHeight() * 0.8f); | |
Bitmap inBitmap = Bitmap.createScaledBitmap(fromDrawable, width, height, false); | |
Bitmap outBitmap = Bitmap.createBitmap(inBitmap); | |
RenderScript renderScript = RenderScript.create(context); | |
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript)); | |
Allocation in = Allocation.createFromBitmap(renderScript, inBitmap); | |
Allocation out = Allocation.createFromBitmap(renderScript, outBitmap); | |
blur.setRadius(BLUR_RADIUS); | |
blur.setInput(in); | |
blur.forEach(out); | |
out.copyTo(outBitmap); | |
renderScript.destroy(); | |
return new BitmapDrawable(context.getResources(), outBitmap); | |
} | |
return drawable; | |
} | |
// returns blur bitmap if api >= 17. returns original bitmap if not. | |
@Nullable | |
public static Bitmap applyBlur(Bitmap bitmap, Context context) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { | |
RenderScript rs = RenderScript.create(context); | |
Bitmap bitmapCopy; | |
int width = Math.round(bitmap.getWidth() * 0.8f); | |
int height = Math.round(bitmap.getHeight() * 0.8f); | |
if (bitmap.getConfig() == Bitmap.Config.ARGB_8888) { | |
bitmapCopy = bitmap; | |
} else { | |
bitmapCopy = bitmap.copy(Bitmap.Config.ARGB_8888, true); | |
} | |
Bitmap outBitmap = Bitmap.createBitmap(width, height, bitmapCopy.getConfig()); | |
Allocation in = Allocation.createFromBitmap(rs, bitmapCopy, | |
Allocation.MipmapControl.MIPMAP_NONE, | |
Allocation.USAGE_SCRIPT); | |
Allocation out = Allocation.createTyped(rs, in.getType()); | |
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, out.getElement()); | |
blur.setRadius(BLUR_RADIUS); | |
blur.setInput(in); | |
blur.forEach(out); | |
out.copyTo(bitmap); | |
rs.destroy(); | |
return outBitmap; | |
} | |
return bitmap; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment