Search code examples
javaandroidbitmaptransparency

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

enter image description here

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

enter image description here

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

Solution

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

    enter image description here