views:

597

answers:

1

I am having some troubles using the CGContext with an iPhone app. I am trying to draw several lines with different colors, but all the lines always end up having to color, which was used last. I tried several approaches I could think of, but haven't been lucky.

I set up a small sample project to deal with that issue. This is my code, I use in the drawRect method. I am trying to draw a red and a blue line:

- (void)drawRect:(CGRect)rect{
    NSLog(@"drawrect!");
    CGContextRef bluecontext = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(bluecontext, 2.0);
    CGContextSetStrokeColorWithColor(bluecontext, [UIColor blueColor].CGColor);
    CGContextMoveToPoint(bluecontext, 1, 1);
    CGContextAddLineToPoint(bluecontext, 100, 100);
    CGContextSetStrokeColorWithColor(bluecontext, [UIColor redColor].CGColor);
    CGContextAddLineToPoint(bluecontext, 200, 100);
    CGContextStrokePath(bluecontext);
}

thanks for your help

+2  A: 

Insert this code just before you set the stroke color the second time:

CGContextStrokePath(bluecontext);
CGContextBeginPath(bluecontext);

All the AddLine and AddOther calls are building a path. The path is drawn with a call like StrokePath, using the most recently set colors and other attributes. You are trying to draw two separate paths, so you must call Begin and Stroke for each path. Begin is sort of implicit when you start drawing, although it does not hurt to call it yourself. The basic flow of drawing is:

CGContextBeginPath(bluecontext); // clears any previous path
// add lines, curves, rectangles, etc...
CGContextStrokePath(bluecontext); // renders the path
drawnonward
Thanks, so this basically runs down to the fact, that I have to render a path with one color, before I draw a path with another color?Creating two contexts, one for the blue lines and one for the red ones does not work, because they are using the same context in the end?
phonecoddy
Yes, for each change in color you must draw the path and clear it. You can do it all in the same context.
drawnonward