2011-11-14 61 views
4

在我的項目中,我有一個填充整個屏幕的位圖。在這個位圖上,我繪製了一條路徑:PorterDuff和路徑

android.graphics.Canvas.drawPath(Path path, Paint paint) 

設置塗料以便描邊和填充路徑的內容。我將實現的是擦除與路徑相交的bitamp部分。我設法使用另一個bitmap而不是路徑,並使用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); 

回答

6

當然,剛繪製的路徑到屏幕外的緩衝區,所以您可以在繪製位圖,像這樣使用它作爲掩模:

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

哦,我看到..所以porterduff」規則只適用於位圖? – Blackbelt

+1

是的,Porter-Duff操作是基於像素的。 –

+0

太棒了!您保存了我的一天,如果不調用cavas.saveLayer,自定義視圖的背景色將變爲黑色。 –