2015-03-25 53 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