在View控件上实现模糊效果两种方法如下:
/**
* 模糊化渲染效果 返回模糊化渲染之后的bitMap 模糊化渲染操作
* @author Ming
*
*/
public class Blur {
private static final int DEFAULT_BLUR_RADIUS = 10;
public static Bitmap apply(Context context, Bitmap sentBitmap) {
return apply(context, sentBitmap, DEFAULT_BLUR_RADIUS);
}
public static Bitmap apply(Context context, Bitmap sentBitmap, int radius) {
final Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
final RenderScript rs = RenderScript.create(context);
final Allocation input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(radius);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmap);
sentBitmap.recycle();
rs.destroy();
input.destroy();
output.destroy();
script.destroy();
return bitmap;
}
}
第二种方法:
private void applyBlur() {
mImageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
mImageView.getViewTreeObserver().removeOnPreDrawListener(this);
mImageView.buildDrawingCache();
Bitmap mBitmap = mImageView.getDrawingCache();
blur(mBitmap, mTextView);
return true;
}
});
}
private void blur(Bitmap bkg, View view) {
float radius = 20;
Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth()),
(int) (view.getMeasuredHeight()), Bitmap.Config.ARGB_8888);
//创建canvas 获取到View在Window里面的位置。移动画布的位置进行绘制
Canvas canvas = new Canvas(overlay);
canvas.translate(-view.getLeft(), -view.getTop());
canvas.drawBitmap(bkg, 0, 0, null);
RenderScript rs = RenderScript.create(getApplication());
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);
//设置当前Background 背景图片时需要判断当前Api的等级是多少。当API等级大于16为分界线
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground((Drawable)(new BitmapDrawable(getResources(), overlay)));
} else {
view.setBackgroundDrawable(new BitmapDrawable(getResources(), overlay));
}
rs.destroy();
}