一·设置声明
renderscriptTargetApi 22 //高斯模糊 renderscriptSupportModeEnabled true
二 .将高斯模糊类到项目
public class ImgViewGs {
/**
* 添加模糊效果
*/
public static void applyBlur(final ImageView imgBackgroung,final View view,final Context context) {
/**
* 1.给imageview对象添加一个视图树的监听,当 image 填充进来的时候,观察者会被触发
* 2.addOnPreDrawListener :添加一个绘画监听
*/
imgBackgroung.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
imgBackgroung.getViewTreeObserver().removeOnPreDrawListener(this);
imgBackgroung.buildDrawingCache();//建立绘制缓冲区
Bitmap bmp =imgBackgroung.getDrawingCache();//建立一个空白bitmap
blur(bmp,view,context);
return true;
}
});
}
/**
* VERSION.SDK_INT 编译版本必须时大于17
* 一个高斯模糊的算法
* @param bkg
* @param view 提供模糊后图片加载范围的
*/
public static void blur(Bitmap bkg, View view, Context context) {
//高斯模糊程度,越大越模糊
float radius =9;
//建立图片绘制区域,和图片像素 ARGB_8888 占四个字节
Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth()),
(int) (view.getMeasuredHeight()), Bitmap.Config.ARGB_8888);
//画板
Canvas canvas =new Canvas(overlay);
canvas.translate(-view.getLeft(), -view.getTop());
canvas.drawBitmap(bkg,0,0,null);
//RenderScript是Android平台上用于运行计算密集任务的框架。RenderScript主要是面向数据并行计算
RenderScript rs = RenderScript.create(context);
//处理模糊
Allocation overlayAlloc = Allocation.createFromBitmap(rs, overlay);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, overlayAlloc.getElement());
blur.setInput(overlayAlloc);//设置输入模糊后的数据流
blur.setRadius(radius);//模糊程度
blur.forEach(overlayAlloc);
overlayAlloc.copyTo(overlay);
view.setBackground(new BitmapDrawable(context.getResources(), overlay));
rs.destroy();//用完以后释放资源
}
}