views:

19

answers:

2

I have the following code the only seems to use the last colour for the whole line..... I want the colour to be changing throughout this. Any ideas?

        CGContextSetLineWidth(ctx, 1.0);

        for(int idx = 0; idx < routeGrabInstance.points.count; idx++)
        {
            CLLocation* location = [routeGrabInstance.points objectAtIndex:idx];

            CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:self.mapView];

            if(idx == 0)
            {
                // move to the first point
                UIColor *tempColor = [self colorForHex:[[routeGrabInstance.pointHeights objectAtIndex:idx] doubleValue]];
                CGContextSetStrokeColorWithColor(ctx,tempColor.CGColor);
                CGContextMoveToPoint(ctx, point.x, point.y);

            }
            else
            {
                    UIColor *tempColor = [self colorForHex:[[routeGrabInstance.pointHeights objectAtIndex:idx] doubleValue]];
                    CGContextSetStrokeColorWithColor(ctx,tempColor.CGColor);
                    CGContextAddLineToPoint(ctx, point.x, point.y);
            }
        }

        CGContextStrokePath(ctx);
A: 

CGContextSetStrokeColorWithColor sets the stroke color in the context. That color is used when you stroke the path, it has no effect as you continue building the path.

You need to stroke each line separately (CGContextStrokePath).

Michal
Thank you, I am calling this via
Lee Armstrong
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
Lee Armstrong
So will this cause me any issues? How will I create a another context?
Lee Armstrong
+1, but you should reword the 'first used' part, it's confusing, as the stroking occurs last in fact.
jv42
You don't have to create another context, just create a path and stoke it in each cycle of your for loop (for each line).
Michal
+1  A: 

The CGContextSetStrokeColorWithColor only changes the state of the context, it does not do any drawing. The only drawing done in your code is by the CGContextStrokePath at the end. Since each call to CGContextSetStrokeColorWithColor overrides the value set by the previous call the drawing will use the last color set.

You need to create a new path, set the color and then draw in each loop. Something like this:

for(int idx = 0; idx < routeGrabInstance.points.count; idx++)
{
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, x1, y1);
    CGContextAddLineToPoint(ctx, x2, y2);
    CGContextSetStrokeColorWithColor(ctx,tempColor.CGColor);
    CGContextStrokePath(ctx);
}
loomer
Perfect answer, slightly adapted but works flawlessly!
Lee Armstrong