Surya Subenthiran
Surya Subenthiran

Reputation: 2217

CoreGraphics - Overlapped path area not filling color

I'm trying to create two rectangle shaped path using core graphics. When I trying to fill the path using color the overlapped are not filling the color.

The code used is

- (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);
} 

The output is

enter image description here

I want the color green to be filled all the closed area. Can any help me how to resolve this issue?

Upvotes: 0

Views: 62

Answers (1)

beyowulf
beyowulf

Reputation: 15331

You are only fill/stroking the entire path, which because of fill rules is causing there to empty space within your path. Instead you should draw the background path fill/stroke it. Then draw the foreground path fill/stroke that. For example:

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

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

You might also consider using UIBezierPath as it is nicer to use in my opinion.

Upvotes: 1

Related Questions