我想在Bitmap
上绘制Canvas
,并应用(线性)Alpha渐变。重要的是,我不想用任何其他颜色覆盖图像;背景(来自我View
后面View
后面的Canvas
s应该只是“闪耀”。为了说明,我的目标是这样的(棋盘图案代表后面的View
)
有人会认为我可以这样做:
Bitmap bitmap = ...;
Paint paint = new Paint();
paint.setShader(new LinearGradient(0, 0, 100, 0, FROM, TO, Shader.TileMode.CLAMP));
canvas.drawBitmap(bitmap, 0, 0, paint);
但此处LinearGradient
的{{1}}和FROM
参数需要是颜色,而不是alpha值;所以我没有办法指明这一点,例如TO
应完全透明,FROM
应完全不透明(不应用任何颜色叠加)。
答案 0 :(得分:6)
使用ComposeShader
,如下所示:
class V extends View {
Bitmap bitmap;
Paint paint = new Paint();
public V(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chrome);
Shader shaderA = new LinearGradient(0, 0, bitmap.getWidth(), 0, 0xffffffff, 0x00ffffff, Shader.TileMode.CLAMP);
Shader shaderB = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(new ComposeShader(shaderA, shaderB, PorterDuff.Mode.SRC_IN));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint);
}
}
答案 1 :(得分:3)
基于this answer about masking,我可以使用辅助屏幕外画布来完成此操作:
Bitmap backing = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
{
Canvas offscreen = new Canvas(backing);
offscreen.drawBitmap(bitmap, 0, 0, null);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
paint.setShader(new LinearGradient(0, 0, 100, 0, 0x00000000, 0xFF000000, Shader.TileMode.CLAMP));
offscreen.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint);
}
canvas.drawBitmap(backing, 0, 0, null);