8

When I use Paint with Color.TRANSPARENT on a normal 2D canvas in Android, I don't get any results and my intention was to get rid of some of the contents on the canvas. I mean the contents that I want to dispose of don't disappear.

This is the code for my Paint:

mPointFillPaint = new Paint();
mPointFillPaint.setColor(Color.TRANSPARENT);
mPointFillPaint.setAntiAlias(true);
mPointFillPaint.setStyle(Paint.Style.FILL);
mPointFillPaint.setStrokeJoin(Paint.Join.MITER); 
ax1mx2
  • 654
  • 1
  • 11
  • 23

2 Answers2

10

The following Paint configuration should help:

mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.TRANSPARENT);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
mPaint.setAntiAlias(true);
Knossos
  • 15,802
  • 10
  • 54
  • 91
Ateeq Ur Rehman
  • 311
  • 1
  • 4
  • 9
  • I have used your code but this code remove some point of below paint object. Like when i draw one line then again i draw another line above last line i draw. And press undo button at my end then i cuts the point of first line where 2nd line draw above the first line. How can i resolve this issue? – Mohit Arora Aug 22 '22 at 06:51
4

I found that using

mPaint.setColor(Color.TRANSPARENT);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));

or

mPaint.setColor(Color.TRANSPARENT);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

just made my paint black.

I had another approach which was to introduce a transparent color to my colors.xml

    <color name="transparentColor">#00ffffff</color>

I opted for the "00ffffff" case but i'm pretty sure that "00000000" will work also, depends on your case.

Final code looks like:

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setColor(getResources().getColor(R.color.transparentColor));
bko
  • 1,038
  • 1
  • 9
  • 17