Android沉浸式开发时,为了让用户专注于内容,避免背景图片的干扰,需要把背景内容模糊掉。 实现效果如下:
Bitmap img = BlurBuilder.blur(this, BitmapFactory.decodeResource(getResources(), R.mipmap.bbg), 3f, 25f); // 模糊值取值 0 < blur <= 25f
为了加速渲染的速度,使用硬件渲染脚本进行高斯模糊,注意模糊值的范围为:(0~25]
package org.tcshare.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
/**
* 模糊图片by yuxiaohei
*/
public class BlurBuilder {
public static Bitmap blur(Context context, Bitmap image, float scale, float radius) {
int width = Math.round(image.getWidth() * scale);
int height = Math.round(image.getHeight() * 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(radius);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}