2012-04-26 118 views
2

我想用紅色填充路徑。這是我的代碼:用特定顏色填充路徑

CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f}; 
CGContextBeginPath(c); 
CGContextSetStrokeColor(c, red); 
CGContextSetFillColorWithColor(c, [UIColor whiteColor].CGColor); 
CGContextMoveToPoint(c, 10, 10); 
CGContextAddLineToPoint(c, 20, 20); 
CGContextAddLineToPoint(c, 20, 40); 
CGContextAddLineToPoint(c, 40, 20); 
CGContextAddLineToPoint(c, 10, 10); 
CGContextStrokePath(c); 
CGContextFillPath(c); 

我知道,我必須使用CGContextSetFillColor()CGContextFillPath(),但它不工作。

我該如何正確地做到這一點?

+0

你能否提供你正在使用以試圖填補代碼路徑? – 2012-04-26 18:58:54

+0

@craig當然,我編輯第一篇文章 – 2012-04-26 19:12:13

+0

解決。在第一篇文章中回答。 – 2012-04-26 19:25:50

回答

3

答案在我的情況是:

CGContextRef context = UIGraphicsGetCurrentContext(); 

//set fill pattern 
UIColor *patternRed = [UIColor colorWithPatternImage:[UIImage imageNamed:@"patternRed.png"]]; 

CGContextSetLineWidth(context, 1.0); 
CGContextSetFillColorWithColor(context, patternRed.CGColor); 

CGMutablePathRef pathRef = CGPathCreateMutable(); 

CGPathMoveToPoint(pathRef, NULL, 0, self.frame.size.height); 
for (int i = 0; i<255; ++i) { 
    CGPathAddLineToPoint(pathRef, NULL, stepX*arrayX[i], self.frame.size.height - (arrayYRed[i]*stepY)); 
} 
CGPathAddLineToPoint(pathRef, NULL, stepX*255, self.frame.size.height); 
CGContextAddPath(context, pathRef); 
CGContextFillPath(context); 

CGPathRelease(pathRef); 
0

您不會在上面的例子中設置一個線寬,所以這裏有一個理智的例子,它將在矩形的左邊畫一條線。直接從功能的drawRect採取

CGContextRef context = UIGraphicsGetCurrentContext(); 
[[UIColor whiteColor] setFill]; 
CGContextFillRect(context, rect); 

CGContextSetLineWidth(context, 2); 
CGFloat gray[4] = {0.5f, 0.5f, 0.5f, 1.0f}; 
CGContextSetStrokeColor(context, gray); 

// left 
CGContextMoveToPoint(context, 0, 0); 
CGContextAddLineToPoint(context, 0, CGRectGetHeight(rect)); 

CGContextStrokePath(context); 
1

爲SWIFT使用:

CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor) 
CGContextFillPath(context) 
+1

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – gunr2171 2015-04-09 20:56:45

+0

我認爲問題是要求正確的方法來改變填充顏色,所以這些是2個簡單的代碼行(順便說一句,很自我解釋)?我需要解釋什麼? – ergunkocak 2015-04-10 08:46:52