2012-12-02 141 views
16

我試圖將畫布繪製操作剪裁成弧形的楔形。但是,在將剪切路徑設置爲畫布後,我沒有得到預期的結果。Canvas.clipPath(路徑)不按預期裁剪

爲了說明,下面是我在做什麼:

enter image description here

path.reset(); 

//Move to point #1 
path.moveTo(rect.centerX(), rect.centerY()); 

//Per the documentation, this will draw a connecting line from the current 
//position to the starting position of the arc (at 0 degrees), add the arc 
//and my current position now lies at #2. 
path.arcTo(rect, 0, -30); 

//This should then close the path, finishing back at the center point (#3) 
path.close(); 

這個工作,而當我簡單地畫這個路徑(canvas.drawPath(path, paint))它繪製楔形,如上圖所示。然而,當我把這個路徑作爲畫布的剪輯路徑,並吸引到它:

//I've tried it with and without the Region.Op parameter 
canvas.clipPath(path, Region.Op.REPLACE); 
canvas.drawColor(Color.BLUE); 

我得到以下的結果,而不是(楔形留給只是爲了顯示參考):

enter image description here

因此,它似乎將剪輯到Path的邊界矩形,而不是Path本身。任何想法發生了什麼?

編輯就像更新一樣,我發現了一個更有效的方法來實現硬件加速。首先,將整個圖像(您將要裁剪的)繪製到離屏位圖中。做一個BitmapShader使用此Bitmap,該着色器設置爲Paint,然後使用該Paint對象繪製楔形路徑:

drawMyBitmap(bitmap); 
Shader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); 
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
paint.setShader(shader); 

@Override 
public void onDraw(Canvas canvas) { 
    canvas.drawArc(rect,   //The rectangle bounding the circle 
        startAngle, //The angle (CW from 3 o'clock) to start 
        sweepAngle, //The angle (CW from 3 o'clock) of the arc 
        true,   //Boolean of whether to draw a filled arc (wedge) 
        paint   //The paint with the shader attached 
    ); 
} 
+1

是否使用

一個Paint創建慧聰或以上或以其他方式使用硬件加速? http://developer.android.com/guide/topics/graphics/hardware-accel.html。如果是這樣,clipPath不受支持並且存在問題。 – Simon

+1

@Simon:噢,天哪。嘿。不幸的是,本週我一直在提及這份文件,但我完全忽略了這一點。禁用硬件加速完美工作!如果您將此作爲答案發布,我會接受它。你是一個救星! – kcoppock

+0

很高興有幫助。祝你好運。 – Simon

回答

9

您是否使用HC或以上或以其它方式使用硬件加速?

如果是這樣,clipPath不受支持並且存在問題。

developer.android.com/guide/topics/graphics/hardware-accel.html

+1

這就是問題所在。 :)將繪圖操作的剪切部分移動到離屏位圖上,然後將其繪製回硬件加速畫布,並且它就像一個魅力!再次感謝! – kcoppock

+1

@kcoppock聽起來有點倒退。你爲什麼不把視圖的圖層類型轉換成軟件,仍然在'onDraw()'中做繪圖? –

+0

@ RichardJ.RossIII這樣做會更有意義。:)當時我對此有點不熟悉。我已經以新的方式編輯了,現在我正在處理這個問題,感謝您的輸入! – kcoppock

2

OP的問題是關於使用剪輯區域,並已由@Simon回答。請記住,但是,有畫充滿弧度的更直接的方式:

mPaint = new Paint(); 
mPaint.setColor(Color.BLUE); 
mPaint.setStyle(Style.FILL); 
mPaint.setAntiAlias(true); 

在繪製時,簡單地畫的路徑:

canvas.drawPath(path, mPaint);