android - PorterDuff 和路径

标签 android drawing porter-duff

在我的项目中,我有一张位图填满了整个屏幕。在此位图上,我用

绘制了一条路径
android.graphics.Canvas.drawPath(Path path, Paint paint)

绘制是为了描边和填充路径的内容而设置的。我要实现的是删除与路径相交的 bitamp 部分。我设法在另一个位图而不是路径上使用 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);

最佳答案

当然,只需绘制到屏幕外缓冲区的路径,这样您就可以在绘制位图时将其用作掩码,如下所示:

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

关于android - PorterDuff 和路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8119936/

相关文章:

java - getActivity() 在 Android java 服务中使用的其他方式

android - RecyclerView - 倒置镜像(或 : let items stick to bottom)

c# - 在 PushSharp 4.0 中构建 GCM 消息

cocoa - 如何在选择后闪烁自定义 NSMenuItem View ?

c - 为什么这段代码在快速移动鼠标时会跳过点?

android - 如何为透明覆盖创建 mask ?

android - 为什么 TextView 的背景会改变它的大小?

背景为黑色时,Android PorterDuff.Mode.CLEAR 无法正常工作

android - Android 中给定 View 下 View 的 PorterDuff 颜色效果

ios - 如何设置不同颜色的不同线条?