I have a custom view and in the onDraw()
, I am trying to perform bitmap masking. I have a squareBitmap
(red color) which fills the whole view, and I have a circleBitmap
(blue color) that acts as the mask. I am using the mode: PorterDuff.Mode.DST_IN
.
The result I am expecting is a RED filled circle. I get that, but I also get a BLACK opaque background. I don't want this opaque background, rather it should be transparent. Figure 1
is the result I got, and Figure 2
is the result that I am looking for.
My code: (I have moved everything inside onDraw()
for the purpose of this question)
protected void onDraw(Canvas canvas) {
final int width = canvas.getWidth();
final int height = canvas.getHeight();
Bitmap circleBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas circleCanvas = new Canvas(circleBitmap);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setStyle(Paint.Style.FILL_AND_STROKE);
p.setColor(Color.BLUE);
circleCanvas.drawCircle(width / 2, height / 2, width / 2, p);
p.setColor(Color.RED);
Bitmap squareBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
Canvas squareCanvas = new Canvas(squareBitmap);
final Rect squareRect = new Rect(0, 0, width, height);
squareCanvas.drawRect(squareRect, p);
Paint q = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawBitmap(squareBitmap, 0, 0, q);
q.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(circleBitmap, 0, 0, q);
q.setXfermode(null);
}
Where am I going wrong? How can I avoid this black opaque background?