使用alpha渐变将位图绘制到画布 [英] Drawing a Bitmap to a Canvas with an alpha gradient

查看:255
本文介绍了使用alpha渐变将位图绘制到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Canvas 上绘制位图,并应用(线性)Alpha渐变。重要的是,我不想用任何其他颜色覆盖图像;背景(来自查看 s后面的查看我将绘制此 Canvas to)应该闪耀。为了说明,我的目标是这样的(棋盘图案表示后面的查看

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 Views 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆