Update: We added the section Preview to visually demonstrate the capabilities.
Recently, we have demonstrated how to integrate the RenderScript support library in Gradle-based projects. In this post, we will showcase the usefulness of having RenderScript available. A common design effect is to blur images for an exceptionally beautiful design. On Android blurring images efficiently was a hassle since the beginning due to the limitation of Java. RenderScript offers an attractive solution.
The Code to Blur Images
Let us jump right to the code:
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
The class provides one static function, which takes a bitmap and returns a blurred version of it. Adjust the two constants BITMAP_SCALE
and BLUR_RADIUS
to your needs. This solution is very fast and easy to integrate. If you need to blur views instead of bitmaps, take a look at the original version of the code on StackOverflow. Please be cautious that you import the support library version of RenderScript (package android.support.v8.renderscript.*
) in order to be compatible to older Android versions. Otherwise, this code requires at least Android API level 17 (Jellybean, Android 4.3).
Let us look at a small example. If you want to set the background of a view as a blurred version of an existing bitmap originalBitmap
, use this code snippet:
Bitmap blurredBitmap = BlurBuilder.blur( getActivity(), originalBitmap );
view.setBackgroundDrawable( new BitmapDrawable( getResources(), blurredBitmap ) );
Preview
Of course, code is never as exciting as a preview of the functionality. Let's take a recipe photo from a our (discontinued) eat foody platform.
A blurry version of it, using our code from above, would look like this:
You can adjust the strength of the blurring by playing with the two constants BITMAP_SCALE
and BLUR_RADIUS
.
Shoot us a tweet if you liked this guide at @futurestud_io.