核心图形多彩线

5
我有以下代码,似乎只使用了最后一个颜色来渲染整行...... 我希望颜色在整行中能够随着变化而改变。你有什么建议吗?
        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个回答

6

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

CGContextSetStrokeColorWithColor 在上下文中设置描边颜色。当你描边路径时,该颜色将被使用,但在继续构建路径时没有任何影响。

你需要分别对每条线进行描边 (CGContextStrokePath)。


谢谢,我正在通过调用此函数。 - Lee Armstrong
  • (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { 在上下文(CGContextRef)ctx中绘制图层(CALayer *)layer的方法:
- Lee Armstrong
这会给我带来任何问题吗?我该如何创建另一个上下文? - Lee Armstrong
+1,但您应该重新措辞“首次使用”的部分,因为实际上描边是最后发生的,这会让人感到困惑。 - jv42
你不需要创建另一个上下文,只需在每个循环(每行)中创建路径并描边即可。 - Michal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接