CoreGraphics多色线

时间:2010-10-26 12:38:20

标签: iphone core-graphics

我有以下代码,似乎只使用整行的最后一种颜色..... 我希望颜色在整个过程中发生变化。有什么想法吗?

        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);

2 个答案:

答案 0 :(得分:4)

CGContextSetStrokeColorWithColor只更改上下文的状态,它不做任何绘图。代码中唯一完成的绘图是最后的CGContextStrokePath。由于每次调用CGContextSetStrokeColorWithColor都会覆盖前一次调用设置的值,因此绘图将使用最后一个颜色集。

您需要创建一个新路径,设置颜色,然后在每个循环中绘制。像这样:

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);
}

答案 1 :(得分:-1)

CGContextSetStrokeColorWithColor在上下文中设置笔触颜色。在描边路径时使用该颜色,在继续构建路径时它不起作用。

您需要单独描绘每一行(CGContextStrokePath)。

相关问题