CoreGraphics - 重叠路径区域不填充颜色

时间:2016-08-30 11:27:35

标签: ios objective-c core-graphics

我正在尝试使用核心图形创建两个矩形路径。当我尝试使用颜色填充路径时,重叠不会填充颜色。

使用的代码是

- (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 个答案:

答案 0 :(得分:1)

您只是填充/抚摸整个路径,因为填充规则导致路径中的空白空。相反,你应该绘制背景路径填充/描边。然后绘制前景路径填充/描边。例如:

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

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

您可能还会考虑使用UIBezierPath,因为我认为它更好用。