Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

java - Drawing a Bitmap to a Canvas with an alpha gradient

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)

linear alpha gradient

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);

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use a ComposeShader, like this:

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...