7

我无法绘制一些用颜色描边的线条,然后用另一个线条填充它们的内部(它们构成一个多边形)。

UIColor *houseBorderColor = [UIColor colorWithRed:(170/255.0) green:(138/255.0) blue:(99/255.0) alpha:1];
CGContextSetStrokeColorWithColor(context, houseBorderColor.CGColor);
CGContextSetLineWidth(context, 3);

// Draw the polygon
CGContextMoveToPoint(context, 20, viewHeight-19.5);
CGContextAddLineToPoint(context, 200, viewHeight-19.5); // base
CGContextAddLineToPoint(context, 300, viewHeight-119.5); // right border
CGContextAddLineToPoint(context, 120, viewHeight-119.5);
CGContextAddLineToPoint(context, 20, viewHeight-19.5);

// Fill it
CGContextSetRGBFillColor(context, (248/255.0), (222/255.0), (173/255.0), 1);
//CGContextFillPath(context);

// Stroke it
CGContextStrokePath(context);

CGContextStrokePath注释掉后,我得到了这个结果:

在此处输入图像描述

但如果我取消注释CGContextStrokePath并填写多边形,颜色会溢出笔画:

在此处输入图像描述

您如何获得这样的结果(无需重做整个绘图过程两次):

在此处输入图像描述

4

3 回答 3

18

您可以使用

CGContextDrawPath(context, kCGPathFillStroke);

代替

CGContextFillPath(context);
CGContextStrokePath(context);

问题是两者都CGContextFillPath()清除CGContextStrokePath(context) 当前路径,这样只有第一个操作成功,第二个操作什么也不画。CGContextDrawPath()结合填充和描边,而不清除它们之间的路径。

于 2013-05-09T13:22:11.327 回答
5

使用 UIBezierPath 你可以这样做:

UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(20, viewHeight-19.5)];
[path addLineToPoint:CGPointMake(200, viewHeight-19.5)];
[path addLineToPoint:CGPointMake(300, viewHeight-119.5)];
[path addLineToPoint:CGPointMake(120, viewHeight-119.5)];
[path addLineToPoint:CGPointMake(20, viewHeight-19.5)];

[[UIColor colorWithRed:(248/255.0) green:(222/255.0) blue:(173/255.0) alpha:1.0] setFill];
[path fill];
[[UIColor colorWithRed:(170/255.0) green:(138/255.0) blue:(99/255.0) alpha:1.0] setStroke];
[path stroke];
于 2013-05-09T13:34:22.790 回答
2

当您在上下文中描边或填充路径时,上下文会为您删除路径(它希望它的工作已完成)。如果要在描边后填充路径,则必须重新添加路径。

最好创建一个CGPathRef path局部变量,构建路径,添加它,描边,再次添加它,填充。

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, 20, viewHeight-19.5);
CGPathAddLineToPoint(path nil, 200, viewHeight-19.5); // base
CGPathAddLineToPoint(path nil, 300, viewHeight-119.5); // right border
CGPathAddLineToPoint(path nil, 120, viewHeight-119.5);
CGPathAddLineToPoint(path nil, 20, viewHeight-19.5);

CGContextAddPath(context, path);
CGContextFillPath(context);

// possibly modify the path here if you need to

CGContextAddPath(context, path);
CGContextStrokePath(context);
于 2013-05-09T13:12:32.290 回答