CoreGraphics Multicolor Line

I have the following code that seems to use the last color for the entire line ..... I want the color to change in all of 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); 
+4
source share
2 answers

CGContextSetStrokeColorWithColor only changes the state of the context, it does not make any drawing. The only drawing made in your code is the CGContextStrokePath at the end. Because 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 that:

 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); } 
+4
source

CGContextSetStrokeColorWithColor sets the color of the stroke in context. This color is used when you stroke the path; it does not affect the continuation of the path.

You need to stroke each line separately ( CGContextStrokePath ).

-1
source

All Articles