How to erase path area from canvas (Android)

Dmitriy picture Dmitriy · Jan 15, 2013 · Viewed 9k times · Source

I need to crop corners on ImageView. Not to round them but erase triangles from each corner.

Seems like the only way to do that is to override onDraw method and erase these areas from canvas using Path. The problem is I have not solid color background, so I need ERASE these areas but not to fill them with some color.

I use following code for that:

@Override
protected void onDraw(Canvas canvas) {
    Path path = new Path();
    path.moveTo(0, 0);
    path.lineTo(20, 0);
    path.lineTo(0, 20);
    path.close();

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    canvas.drawPath(path, paint);
    super.onDraw(canvas);
}

But the corner makes black but not transparent. Could you help me? Or probably you know better solution for my task. Here is how it looks like.

enter image description here

Answer

daniribalbert picture daniribalbert · Mar 6, 2014

In order to draw with a transparent color you must use Paint setXfermode which will only work if you set a bitmap to your canvas. If you follow the steps below you should get the desired result.

  1. Create a canvas and set its bitmap.

    mCanvas = new Canvas();
    mBitmap= Bitmap.createBitmap(scrw, scrh, Config.ARGB_8888);
    mCanvas.setBitmap(mBitmap);
    
  2. When you want to erase something you just need to use setXfermode.

    if (isErasing)
       mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    else
       mPaint.setXfermode(null);
    
  3. Now you should be able draw with a transparent color using:

    mCanvas.drawPath(yourpath, mPaint);