I'm trying to draw some simples lines with the iPhone/Touch SDK. I'd like to be able to change the color of the lines, but calling CGContextSetRGBStrokeColor doesn't seem to affect the drawn lines that are made with CGContextAddLineToPoint until the actual call to CGContextStrokePath is made. So if I make multiple calls to change the color, only the one made just before CGContextStrokePath has any effect. Here's what I mean:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 0, 0);
CGContextSetRGBStrokeColor(ctx,1,0,0,1);
CGContextAddLineToPoint(ctx, 100, 100);
//CGContextStrokePath(ctx);
CGContextSetRGBStrokeColor(ctx,0,1,0,1);
CGContextAddLineToPoint(ctx, 200, 300);
//CGContextStrokePath(ctx);
CGContextSetRGBStrokeColor(ctx,0,0,1,1);
CGContextStrokePath(ctx);
}
I assume I'm doing something horribly wrong, I just can't quite figure out what. I thought that if I added the CGContextStrokePath calls, that would help, it doesn't.
See discussion below for how I got to the corrected code:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, 0, 0);
CGContextSetRGBStrokeColor(ctx,1,0,0,1);
CGContextAddLineToPoint(ctx, 100, 100);
CGContextStrokePath(ctx);
CGContextClosePath(ctx);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, 100, 100);
CGContextSetRGBStrokeColor(ctx,0,1,0,1);
CGContextAddLineToPoint(ctx, 200, 300);
CGContextStrokePath(ctx);
}