【问题标题】:PorterDuff and Path波特达夫和路径
【发布时间】:2011-12-28 12:41:21
【问题描述】:

在我的项目中,我有一个填充整个屏幕的位图。在这个位图上,我用

画了一条路径
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);

【问题讨论】:

    标签: android drawing porter-duff


    【解决方案1】:

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

    // 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 的规则只适用于位图?
    • 是的,Porter-Duff 操作是基于像素的。
    • 太棒了!你救了我的命,如果不调用 cavas.saveLayer,自定义视图的背景颜色将为黑色。
    猜你喜欢
    • 2021-12-27
    • 2018-01-26
    • 1970-01-01
    • 2019-06-07
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多