Drawing on Canvas - PorterDuff.Mode.CLEAR draws black! Why?

cadavre picture cadavre · Aug 22, 2013 · Viewed 20.9k times · Source

I'm trying to create a custom View which works simple: there is a Bitmap which is revealed by arc path - from 0deg to 360deg. Degrees are changing with some FPS.

So I made a custom View with overridden onDraw() method:

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
    arcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
    canvas.drawArc(arcRectF, -90, currentAngleSweep, true, arcPaint);
    arcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, circleSourceRect, circleDestRect, arcPaint);
}

arcPaint is initialized as follows:

arcPaint = new Paint();
arcPaint.setAntiAlias(true);
arcPaint.setColor(Color.RED); // Color doesn't matter

Now, everything draws great, but... the background is BLACK in whole View.

If I set canvas.drawColor(..., PorterDuff.Mode.DST) and omit canvas.drawBitmap() - the arc is drawn properly on transparent background.

My question is - how to set PorterDuff modes to make it work with transparency?

Of course bitmap is 32-bit PNG with alpha channel.

Answer

Nitesh Tarani picture Nitesh Tarani · Jun 17, 2017

PorterDuff.Mode.CLEAR doesn't work with hardware acceleration. Just set

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null); 

Works perfectly for me.