我有一个带不同颜色的视图。我需要模糊该视图的背景。例如,有一个LinearLayout,在其中有一个显示一些应用程序的Grid,这个LinearLayout(Gridview容器)有颜色(红色/绿色/黑色等,没有图像)。现在我需要模糊LinearLayout的背景。
这张图片是我要实现的效果:
我使用Android Render脚本来完成所有操作,因为我有很多片段,每个片段都有颜色的背景,所以我认为Render是最好的选择,否则在滑动View Pager时可能会出现卡顿。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.activity_main);
view=(View)findViewById(R.id.view);
Bitmap blurredBitmap = blur( this, getBitmapFromView(view) );
view.setBackgroundDrawable( new BitmapDrawable( getResources(), blurredBitmap ) );
mainLayout.setBackgroundResource(R.drawable.wallp);
}
public static Bitmap getBitmapFromView(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_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(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
现在的问题是,如果我在LinearLayout的背景中设置颜色,则会出现以下错误:
Caused by: java.lang.IllegalArgumentException: 宽度和高度必须大于0。我们能否模糊具有颜色但没有图像的视图的背景?
请注意,本文中的HTML标签已保留,以便在需要时使用。