PorterDuff and Path

5
在我的项目中,我有一个填满整个屏幕的位图。在这个位图上,我画了一条路径。
android.graphics.Canvas.drawPath(Path path, Paint paint)

这里的绘画是为了描绘和填充路径内容。我的目标是擦除与路径相交的位图部分。我已经成功地使用porter duff规则在另一个位图上实现了相同的行为。是否有可能在路径上做到同样的事情呢?

    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);
1个回答

7
当然,只需将路径绘制到离屏缓冲区中,这样您就可以在绘制位图时使用它作为掩模,类似于以下内容:
// 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);

哦,我明白了。所以PorterDuff规则只适用于位图? - Blackbelt
1
是的,Porter-Duff 操作是基于像素的。 - Martin Nordholts
太好了!你救了我的一天,如果不调用canvas.saveLayer,自定义视图的背景颜色将是黑色。 - Jishi Chen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接