简体   繁体   中英

Unable to modify Bitmap to be transparent in Android

I am trying to draw a transparent circle on a Bitmap in android. I have three primary variables:

        mask = Bitmap.createBitmap(this.getWidth(),this.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas can = new Canvas(mask);
        Paint clear = new Paint();

If I do the following, I get my expected results:

clear.setColor(Color.TRANSPARENT);
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

在此处输入图片说明

However, if I draw something else on the canvas first, then try to clear it out with transparency, the old data remains. For example:

clear.setColor(Color.argb(255,255,0,0));
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);
clear.setColor(Color.TRANSPARENT);
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

在此处输入图片说明

I only see a giant red square. The bottom two lines are supposed to "erase" the filled red to make it transparent again. Ultimately the mask is drawn on another canvas like this:

@Override
public void onDraw(Canvas c)
{
    c.drawBitmap(mask,0,0,null);

    super.onDraw(c);
}

As it turns out it does have to do with the Paint object and setting the Xfermode...

    mask = Bitmap.createBitmap(this.getWidth(),this.getHeight(), 
    Bitmap.Config.ARGB_8888);
    Canvas can = new Canvas(mask);

    Paint clear = new Paint();
    clear.setColor(Color.argb(255,255,0,0));
    can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

    PorterDuffXfermode xfer = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    clear.setXfermode(xfer);
    clear.setColor(Color.TRANSPARENT);
    can.drawCircle(this.getWidth()/2, this.getHeight()/2, this.getHeight()/2, clear);

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM