I have a background image that takes up the whole screen. I am drawing canvas over the background and setting its color to white so you can't see the image yet. What I am trying to achieve is to then draw a transparent shape onto the white canvas and have the background image show through where that shape is. I am using a surfaceView and implementing SurfaceView.Callback
.
Asked
Active
Viewed 1.7k times
8
2 Answers
10
to draw transparent shape follow this code
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
//draw any shape, here I am drawing Rect shape
Rect rect=new Rect(left, top, right, bottom);
canvas.drawRect(rect,paint);

Scarecrow
- 4,057
- 3
- 30
- 56
-
7it leave the area black – Sagar Devanga Feb 26 '17 at 18:35
-
`PorterDuff.Mode.CLEAR` doesn't work with hardware acceleration, use `View.LAYER_TYPE_SOFTWARE` https://stackoverflow.com/a/44607874/3315714 – Ilia Nov 16 '21 at 11:25
8
You should make the white color transparent:
public void draw(Canvas canvas)
{
final RectF rectF = new RectF();
final Paint paint = new Paint();
paint.setARGB(128, 255, 255, 255);
rectF.set(0,0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRect(rectF, paint);
}

david
- 1,311
- 12
- 32