图片模糊处理
2018-04-03 本文已影响0人
jiangjh
RenderScript是处理Bitmap的对象的,对于Drawable需要先转成Bitmap然后先处理。但Drawable的子类有多种BitmapDrawable,GradientDrawable等
private Bitmap blurDrawable(Drawable drawable, int width, int height) {
if (Build.VERSION.SDK_INT >= 17) {
// Bitmap blurTemplate = ((BitmapDrawable) primaryBg).getBitmap();
Bitmap blurTemplate = drawableToBitmap(primaryBg, width, height);
RenderScript rs = RenderScript.create(getContext());
Allocation input = Allocation.createFromBitmap(rs, blurTemplate);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(20);
script.setInput(input);
script.forEach(output);
output.copyTo(blurTemplate);
rs.destroy();
return blurTemplate;
}
return null;
}
public static Bitmap drawableToBitmap(Drawable drawable, int width, int height) {
// 取 drawable 的长宽 - GradientDrawable获取的宽度和高度为-1
// int w = drawable.getIntrinsicWidth();
// int h = drawable.getIntrinsicHeight();
int w = width;
int h = height;
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}