1

I need to paint a series of path in a CGContext as a block. These path are drawn by the user so I can not determine their direction. I use the following code snippet to draw the path:

CGContextSaveGState(context);
UIBezierPath *fillPath = [ UIBezierPath bezierPath ];

for ( UIBezierPath *path in arrayOfPaths ) {
    [ fillPath appendPath:path ];
}

CGContextAddPath(context, fillPath.CGPath );
CGContextSetFillColorWithColor( context, [[UIColor GreenColor ] colorWithAlphaComponent:0.3 ].CGColor );
CGContextFillPath(context);

However if the paths were created in reverse directions the resulting drawing seems to produce a drawing where the overlapping section is knocked out, equivalent of setting the even-odd rule to Yes.

Any suggestions?

reza23
  • 3,079
  • 2
  • 27
  • 42

1 Answers1

0

You could surround the lines that fill each path with CGContextSaveGState/CGContextRestoreGState instructions. That way you would start "from scratch", ie. with a clean path stack, on each filling.

Edit: I've got a nice wrapping function for this:

void CGContextBlock(CGContextRef ctx, void (^block)())
{
    CGContextSaveGState(ctx);
    block();
    CGContextRestoreGState(ctx);
}

Use it like that:

CGContextSetFillColorWithColor(context, [UIColor GreenColor].CGColor);
for (UIBezierPath *path in arrayOfPaths)
{
    CGContextBlock(context, ^{
        CGContextAddPath(context, path.CGPath);
        CGContextFillPath(context);
    });
}
Cyrille
  • 25,014
  • 12
  • 67
  • 90
  • I don't think this would work as I need to make the block colour semi transparent, which I forgot to mention in my initial question. This would result for each time the shape to be drawn on to the previous one and hence you would not get a flat semitransparent colour – reza23 Mar 24 '14 at 11:54