2016-08-30 93 views
0

我試圖創建兩個使用核心圖形的矩形形狀的路徑。當我嘗試使用顏色填充路徑時,重疊不填充顏色。CoreGraphics - 重疊的路徑區域不填充顏色

使用的代碼

- (void)drawRect:(CGRect)rect { 

    CGPoint topLeft = CGPointMake(121, 116); 
    CGPoint topRight = CGPointMake(221, 216); 

    CGPoint middleLeft = CGPointMake(121, 180); 
    CGPoint middleRight = CGPointMake(221, 280); 

    CGPoint bottomLeft = CGPointMake(250, 56); 
    CGPoint bottomRight = CGPointMake(350, 156); 

    CGMutablePathRef subpath1 = CGPathCreateMutable(); 
    CGPathMoveToPoint(subpath1, NULL, topLeft.x, topLeft.y); 
    CGPathAddLineToPoint(subpath1, NULL, topRight.x, topRight.y); 
    CGPathAddLineToPoint(subpath1, NULL, middleRight.x, middleRight.y); 
    CGPathAddLineToPoint(subpath1, NULL, middleLeft.x, middleLeft.y); 
    CGPathAddLineToPoint(subpath1, NULL, topLeft.x, topLeft.y); 
    CGPathCloseSubpath(subpath1); 

    CGMutablePathRef subpath2 = CGPathCreateMutable(); 
    CGPathMoveToPoint(subpath2, NULL, middleLeft.x, middleLeft.y); 
    CGPathAddLineToPoint(subpath2, NULL, middleRight.x, middleRight.y); 
    CGPathAddLineToPoint(subpath2, NULL, bottomRight.x, bottomRight.y); 
    CGPathAddLineToPoint(subpath2, NULL, bottomLeft.x, bottomLeft.y); 
    CGPathAddLineToPoint(subpath2, NULL, middleLeft.x, middleLeft.y); 
    CGPathCloseSubpath(subpath2); 

    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathAddPath(path, NULL, subpath1); 
    CGPathAddPath(path, NULL, subpath2); 
    CGPathCloseSubpath(path); 


    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.19 green:0.42 blue:0.09 alpha:1.0].CGColor); 
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.19 green:0.42 blue:0.09 alpha:1.0].CGColor); 
    CGContextSetBlendMode(context, kCGBlendModeMultiply); 
    CGContextSetAlpha(context, 1.0); 

    CGContextAddPath(context, path); 
    CGContextDrawPath(context, kCGPathFillStroke); 
} 

輸出是

enter image description here

我想要的顏色綠色填充所有封閉區域。任何可以幫助我如何解決這個問題?

回答

1

您只填充/撫摸整個路徑,這是因爲填充規則導致您的路徑中出現空白空間。相反,你應該繪製背景路徑填充/描邊它。然後繪製前景路徑填充/描邊。例如:

CGContextAddPath(context, subpath1); 
CGContextDrawPath(context, kCGPathFillStroke); 

CGContextAddPath(context, subpath2); 
CGContextDrawPath(context, kCGPathFillStroke); 

您也可以考慮使用UIBezierPath,因爲它是更好的在我看來使用。