在我的项目中,我有一个位图填充整个屏幕。在这个位图上,我用
画了一条路径android.graphics.Canvas.drawPath(Path path, Paint paint)
设置为描边和填充路径的内容。我要实现的是擦除与路径相交的位放大器部分。我已经设法在另一个位图上获得相同的行为,而不是使用路径,并使用波特达夫规则。是否有机会对路径做同样的事情?
mPaintPath.setARGB(100, 100, 100, 100);// (100, 100, 100, 100)
mPaintPath.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintPath.setAntiAlias(true);
mPath.moveTo(x0, y0));
mPath.lineTo(x1, y1);
mPath.lineTo(x2, y2);
mPath.lineTo(x3, y3);
mPath.lineTo(x0, y0);
mPath.close();
c.drawPath(mPath, mPaintPath);
当然,只要将路径绘制到屏幕外缓冲区,这样当你绘制位图时就可以将其用作掩码,就像这样:
// Create an offscreen buffer
int layer = c.saveLayer(0, 0, width, height, null,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
// Setup a paint object for the path
mPaintPath.setARGB(255, 255, 255, 255);
mPaintPath.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintPath.setAntiAlias(true);
// Draw the path onto the offscreen buffer
mPath.moveTo(x0, y0);
mPath.lineTo(x1, y1);
mPath.lineTo(x2, y2);
mPath.lineTo(x3, y3);
mPath.lineTo(x0, y0);
mPath.close();
c.drawPath(mPath, mPaintPath);
// Draw a bitmap on the offscreen buffer and use the path that's already
// there as a mask
mBitmapPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
c.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
// Composit the offscreen buffer (a masked bitmap) to the canvas
c.restoreToCount(layer);
如果你能承受混叠,有一个更简单的方法:只是设置一个剪辑路径(注意Region.Op.DIFFERENCE
的使用,它会导致路径的内部被剪辑掉,而不是剪辑路径之外的一切):
// Setup a clip path
mPath.moveTo(x0, y0);
mPath.lineTo(x1, y1);
mPath.lineTo(x2, y2);
mPath.lineTo(x3, y3);
mPath.lineTo(x0, y0);
mPath.close();
c.clipPath(mPath, Op.DIFFERENCE);
// Draw the bitmap using the path clip
c.drawBitmap(mBitmap, 0, 0, mBitmapPaint);