RenderScript是處理Bitmap的對象的概行,對于Drawable需要先轉(zhuǎn)成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;
// 建立對應(yīng) bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立對應(yīng) bitmap 的畫布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 內(nèi)容畫到畫布中
drawable.draw(canvas);
return bitmap;
}