2015-03-25 97 views
0

我正在试图画出一个笔画和填充但不填充的形状。CGContextDrawPath只能画笔而不能填充

这里是我的代码:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{ 
    CGMutablePathRef pathRef = CGPathCreateMutable(); 
    CGContextBeginPath(ctx); 

    self.dottedLineColor = [UIColor whiteColor]; 
    self.solidLineColor = [UIColor blackColor]; 
    CGContextSetStrokeColorWithColor(ctx, [self.dottedLineColor CGColor]); 
    CGContextSetFillColorWithColor(ctx, [UIColor blackColor].CGColor); 

    CGContextSetLineWidth(ctx, 11.0); 

    for (NSArray *array in previewPoints){ 
      CGPoint pointMadeFromString1 = CGPointFromString([array objectAtIndex:0]); 
      CGPoint pointMadeFromString2 = CGPointFromString([array objectAtIndex:1]); 

      CGPathMoveToPoint(pathRef, NULL, pointMadeFromString1.x, pointMadeFromString1.y); 
      CGPathAddLineToPoint(pathRef, NULL, pointMadeFromString2.x, pointMadeFromString2.y); 
      /* 
      CGContextMoveToPoint(ctx, pointMadeFromString1.x, pointMadeFromString1.y); 
      CGContextAddLineToPoint(ctx, pointMadeFromString2.x, pointMadeFromString2.y); 

      CGContextSetLineWidth(ctx, 11.0); 
      const CGFloat dashPattern[2] = {2, 0}; 
      CGContextSetLineDash(ctx, 2, dashPattern, 2); 
      CGContextStrokePath(ctx); 
      */ 
    } 
    CGContextAddPath(ctx, pathRef); 
    CGContextClosePath(ctx); 

    CGContextDrawPath(ctx, kCGPathFillStroke); 
    CGContextFillPath(ctx); 
} 

这里是它现在的样子:

enter image description here

中间的区域应该是黑色的。

我该如何解决这个问题?

回答

2

问题是我每次使用CGPathMoveToPoint这意味着它不能填充,因为它实际上并不是封闭的路径。我将它切换,以便只有数组中的第一项使用CGPathMoveToPoint,然后所有其他项将使用CGPathAddLineToPoint