我该如何在Android中给线性布局添加透明渐变背景?目前该布局的背景是模糊的图像,但我需要让该图像在布局顶部略微透明,并在底部变为不透明。
该布局嵌套在视差滚动视图中,因此该布局可以滑动到头部图像的顶部。
我通过以下方式生成了模糊的可绘制对象:
final View content = img_header;
if (content.getWidth() > 0) {
Bitmap image = BlurBuilder.blur(content);
BitmapDrawable background = new BitmapDrawable(image);
ll_parent_layout.setBackground(background);
} else {
content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Bitmap image = BlurBuilder.blur(content);
BitmapDrawable background = new BitmapDrawable(image);
ll_parent_layout.setBackground(background);
}
});
}
模糊生成器的代码如下:
public class BlurBuilder {
private static final float BITMAP_SCALE = 1f;
private static final float BLUR_RADIUS = 25f;
public static Bitmap blur(View v) {
return blur(v.getContext(), getScreenshot(v));
}
public static Bitmap blur(Context ctx, 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);
/// compress bitmap here
RenderScript rs = RenderScript.create(ctx);
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;
}
public static Bitmap blur(Context ctx, Bitmap image, float scale, float radius) {
int width = Math.round(image.getWidth() * scale);
int height = Math.round(image.getHeight() * scale);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(ctx);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(radius);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
private static Bitmap getScreenshot(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
}