填充具有特定颜色的路径

时间:2012-04-26 18:56:53

标签: objective-c drawing core-graphics cgcontext

我想用红色填充路径。这是我的代码:

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(),但它不起作用。

我该如何正确地做到这一点?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

快速使用:

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

答案 2 :(得分:0)

你没有在上面的例子中设置线宽,所以这里是一个明智的例子,它将在rect的左侧绘制一条线。直接取自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);