用一种颜色绘制一个多边形的笔画,另一个用于填充?

我在绘制一些用颜色抚摸的线条,然后用另一个线条填充它们的内部(它们构成一个多边形)时遇到了麻烦。

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并填充多边形,颜色会溢出笔画:

在这里输入图像说明

你如何达到这样的结果(不必重复整个绘图程序两次):

在这里输入图像说明

您可以使用

 CGContextDrawPath(context, kCGPathFillStroke); 

代替

 CGContextFillPath(context); CGContextStrokePath(context); 

问题是CGContextFillPath()CGContextStrokePath(context) 清除当前path,所以只有第一个操作成功,第二个操作什么都没有。 CGContextDrawPath()结合填充和描边而不清除之间的path。

使用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]; 

当您在上下文中描述或填充path时,上下文将为您删除path(它期望它的工作已经完成)。 如果要在抚摸它之后填充它,则必须再次添加path。

最好创build一个CGPathRef path局部variables,build立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);