How to erase path area from canvas (Android)

前提是你 提交于 2019-12-05 15:12:41

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);

You can clip your canvas object:

@Override
protected void onDraw(Canvas canvas) {
    final Path path = new Path();
    final int count = canvas.save();

    path.moveTo(0, 20);
    path.lineTo(20, 0);
    path.lineTo(getWidth(), 0);
    path.lineTo(getWidth(), getHeight());
    path.lineTo(0, getHeight());
    path.close();

    canvas.clipPath(path);
    super.onDraw(canvas);
    canvas.restoreToCount(count);
}

Please note Canvas.clipPath doesn't work on Android 3.0 or above with enabled hardware acceleration .

use this Line

 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

instead of this

 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!