1:现在不推荐使用自定义Region.Op的所有方法,因此现在只能使用两种方法变体:clipRect / clipPath(表示Region.Op.INTERSECT)和clipOutRect / clipOutPath(表示Region.Op.DIFFERENCE).要实现类似于Region.Op.REPLACE的功能,必须使用save()和restore()方法:
canvas.save(); // IMPORTANT: save current state of clip and matrix (i.e. unclipped state) (let's say it's state #1)
canvas.clipRect(0, 0, 100, 100); // do some clipping
canvas.drawLine(...); // do some clipped drawing
canvas.restore(); // IMPORTANT: get back to previously saved (unclipped) state of the canvas (restores state #1)
canvas.save(); // now save again the current state of canvas (clip and matrix) (it's state #2)
canvas.clipRect(200, 200, 400, 400); // now we can do some other clipping (as we would do with Region.Op.REPLACE before)
canvas.drawLine(...); // and some other drawing
canvas.restore(); // get back go previously saved state (to state #2)
注意Canvas在内部使用堆栈,因此您甚至可以在不同时刻多次调用save().你不能调用canvas.restore()多次调用canvas.save().
同样重要的是,调用canvas.restore()会更改剪辑rect(与调用canvas.save()时的值相同).因此,必须在需要应用剪切的所有绘制方法之后仔细放置restore()调用.
2:可能是因为一些性能优化.我想我读到了某个地方(我现在找不到),对于GPU上的硬件加速,他们只能使用INTERSECT / DIFFERENCE剪辑操作,其他必须回退到CPU处理.这可能是原因.
3:正如他们在文档中所说,它将停止在Android P中工作(可能仅在针对Android P时):
As of API Level API level Build.VERSION_CODES.P only INTERSECT and DIFFERENCE are valid Region.Op parameters.