使用 alpha 渐变将位图绘制到画布上 [英] Drawing a Bitmap to a Canvas with an alpha gradient
问题描述
我想在 Canvas
上绘制一个 Bitmap
,并应用(线性)alpha 渐变.重要的一点是我不想用任何其他颜色覆盖图像;背景(来自 View
后面的 View
,我要把这个 Canvas
绘制到)应该只是闪耀".为了说明,我的目标是这样的(棋盘模式代表后面的View
)
I'd like to draw a Bitmap
on a Canvas
, with a (linear) alpha gradient applied. The important point is that I don't want to overlay the image with any other color; the background (coming from the View
s behind the View
that I'd be drawing this Canvas
to) should just "shine through". To illustrate, my goal would be something like this (the checkerboard pattern represents the View
behind)
有人会认为我可以做这样的事情:
One would think that I could do something like this:
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
的 FROM
和 TO
参数在这里需要是颜色,而不是 alpha 值;所以我没有办法指定例如FROM
应该完全透明,TO
应该完全不透明(不应用任何颜色叠加).
but LinearGradient
's FROM
and TO
arguments here would need to be colors, not alpha values; so there's no way that I see to specify that e.g. FROM
should be fully transparent and TO
should be fully opaque (without applying any color overlay).
推荐答案
使用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);
}
}
这篇关于使用 alpha 渐变将位图绘制到画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!