How to set Gaussian blur for Android background?

To set a background with a Gaussian blur effect in an Android app, you can use the following method:

  1. Setting the background using XML layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_blur">
    
    <!-- Your other layout views here -->

</RelativeLayout>
  1. Create a file named bg_blur.xml in the res/drawable directory and define a Gaussian blur effect in the file.
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/your_background_image"
    android:gravity="center"
    android:alpha="0.6"/>
  1. Create a utility class BlurUtils.java for applying Gaussian blur to background images.
public class BlurUtils {
    
    public static Bitmap blurBitmap(Context context, Bitmap bitmap, float radius) {
        RenderScript rs = RenderScript.create(context);
        Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
        Allocation output = Allocation.createTyped(rs, input.getType());
        
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(radius);
        script.setInput(input);
        script.forEach(output);
        
        output.copyTo(bitmap);
        
        rs.destroy();
        
        return bitmap;
    }
}
  1. Use the above utility class in Activity or Fragment to apply Gaussian blur effect to the background image that needs to be set, and then set it as the background.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_background_image);
Bitmap blurredBitmap = BlurUtils.blurBitmap(this, bitmap, 25f);
Drawable drawable = new BitmapDrawable(getResources(), blurredBitmap);
yourRelativeLayout.setBackground(drawable);

By following the above steps, you can set a Gaussian blur background effect in your Android application.

bannerAds