2016-08-30 92 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,因为它是更好的在我看来使用。