iPhone CGContext: drawing two lines with two different colors

phonecoddy picture phonecoddy · Jun 15, 2010 · Viewed 24k times · Source

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 the color which was used last. I tried several approaches, 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

Answer

drawnonward picture drawnonward · Jun 15, 2010

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