2012-08-29 34 views
1

我需要用drawRect()方法填充UIView中的'還原多邊形' - 視圖中的所有內容都用除多邊形之外的某種顏色填充。UIView drawRect():填充除多邊形以外的所有東西

我有了這個代碼,以繪製一個簡單多邊形:

CGContextBeginPath(context); 
for(int i = 0; i < corners.count; ++i) 
{ 
    CGPoint cur = [self cornerAt:i], next = [self cornerAt:(i + 1) % corners.count]; 
    if(i == 0) 
     CGContextMoveToPoint(context, cur.x, cur.y); 
    CGContextAddLineToPoint(context, next.x, next.y); 
} 
CGContextClosePath(context); 
CGContextFillPath(context); 

我發現了一個類似的問題,但在C#中,沒有對象 - C:c# fill everything but GraphicsPath

+0

您可以用填充顏色填充整個視圖,也比使用清晰的彩色 – Sohaib

+0

嘗試同樣喜歡在C#代碼繪製您的多邊形過它:CGContextAddRect(背景下,self.bounds)CGContextClosePath – Felix

回答

3

可能是最快的方法是設置一個片段:

// create your path as posted 
// but don't fill it (remove the last line) 

CGContextAddRect(context, self.bounds); 
CGContextEOClip(context); 

CGContextSetRGBFillColor(context, 1, 1, 0, 1); 
CGContextFillRect(context, self.bounds); 

兩個其他答案建議先填寫一個矩形,然後畫在上面清晰的彩色形狀。兩者都省略了必要的混合模式。這裏有一個工作版本:

CGContextSetRGBFillColor(context, 1, 1, 0, 1); 
CGContextFillRect(context, self.bounds); 

CGContextSetBlendMode(context, kCGBlendModeClear); 

// create and fill your path as posted 

編輯:這兩種方法都需要backgroundColorclearColoropaque設置爲NO。

第二編輯:原來的問題是關於核心圖形。當然,還有其他方法可以掩蓋部分視圖。最值得注意的是CALayermask屬性。

您可以將此屬性設置爲CAPathLayer的實例,該實例包含剪輯路徑以創建模具效果。

+0

謝謝,它的工作原理!第一種解決方案比較好,因爲它不會裁剪整個視圖,並且有可能在裁剪多邊形內部繪製其他東西。另外,它以某種方式將「不透明」設置爲「YES」。 :) – dreamzor

+0

@dreamzor很高興我能幫到你。儘管如此,我不會依賴這個事實,即它使用'opaque = YES'。 –

+0

已經有一段時間了,但現在我發現這種方式太慢了。可以通過其他方式完成,使用CALayer還是其他方法?它看起來不是一個非常艱苦的繪畫工作... – dreamzor

0

中的drawRectü可以設置背景UR與色彩觀的顏色ü要

self.backgroundColor = [UIcolor redColor]; //set ur color 

,然後繪製多邊形烏爾做的方式。

CGContextBeginPath(context); 
for(int i = 0; i < corners.count; ++i) 
{ 
    CGPoint cur = [self cornerAt:i], next = [self cornerAt:(i + 1) % corners.count]; 
    if(i == 0) 
     CGContextMoveToPoint(context, cur.x, cur.y); 
    CGContextAddLineToPoint(context, next.x, next.y); 
} 
CGContextClosePath(context); 
CGContextFillPath(context); 

希望它可以幫助...編碼快樂:)

+0

之前,我要建議的同樣的事情@Resh32也有類似的想法 – Kezzer

+0

你不應該在'drawRect'中設置backgroundColor。此外,您的方法不會呈現透明的形狀。 –

0

創建一個新的CGLayer,與外面的顏色填充,然後使用一個清晰​​的彩色畫的多邊形。

layer1 = CGLayerCreateWithContext(context, self.bounds.size, NULL); 
context1 = CGLayerGetContext(layer1); 

[... fill entire layer ...] 

CGContextSetFillColorWithColor(self.context1, [[UIColor clearColor] CGColor]); 

[... draw your polygon ...] 

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextDrawLayerAtPoint(context, CGPointZero, layer1); 
+0

你需要什麼CGLayer?似乎不必要的開銷給我。 –

+0

另外,使用默認混合模式(porter-duff over)繪製清晰的顏色是沒有任何操作的。 –

+0

如果主環境已經繪製了其他元素(我不知道應用程序的其餘部分),則需要CGLayer。 – Resh32