5
votes

I have created a complex UIBezierPath that is composed of several path segments, solid, dashed, lines, colors, arcs, etc. So I have this and now I want to render it to a CGContext.

So, I convert it to a CGPathReference using

CGPathRef cgPath = CGPathCreateCopy(aBezierPath.CGPath);

The problem is this: in theory, if I want to draw a path on a CGContext, I have to define the stroke width, color, line style, blending mode, etc. for each segment that needs to be different, but the UIBezierPath I have already created contains all this information.

So, I wonder if there is a way to just to "stamp" the CGPath as it is on the CGContext, so it will be stamped with all the original information?

thanks.

1
Can you not just use the UIBezierPath's stroke method?Tom Irving

1 Answers

6
votes

DR, you're right: it is very confusing!

But I think Tom is correct, just use [aBezierPath stroke].

So, it would be something like this:

REF is a (CGContextRef) which you have built.

YOURBEZIERPATH is a (UIBezierPath*).

Inevitably you have to deal with the "drawing upside down" issue, so:

UIGraphicsPushContext(REF);
CGContextSaveGState(REF);
CGContextTranslateCTM(REF, 0, the height*);
CGContextScaleCTM(REF, 1.0, -1.0);
[YOURBEZIERPATH stroke];
CGContextRestoreGState(REF);
UIGraphicsPopContext();

So that's it.

Re your comment below: I have an array of UIBezierPaths. Each bezier has its own style and color.

Does this help? ... Replace the one "stroke" call, with a for loop:

UIGraphicsPushContext(REF);
CGContextSaveGState(REF);
CGContextTranslateCTM(REF, 0, the height*);
CGContextScaleCTM(REF, 1.0, -1.0);

for each of YOURBEZIERPATH in your array...
    {
    CGContextSaveGState(REF);
    [YOURBEZIERPATH stroke];
    CGContextRestoreGState(REF);
    }

CGContextRestoreGState(REF);
UIGraphicsPopContext();

You actually do not need to bother using aBezierPath.CGPath, or, a copy thereof.

Again you are right, it is very confusing, the two worlds of UI and CG !!


*the height: often something like self.frame.size.height. I just include this for anyone looking for general example code in the future.