2010-10-26 36 views
4

我有以下代碼,似乎只使用最後一種顏色作爲整行..... 我希望顏色在整個過程中都會發生變化。有任何想法嗎?CoreGraphics Multi-Colored Line

 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

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

完美的答案,略有改動,但完美無瑕! – 2010-10-26 12:58:06

-1

CGContextSetStrokeColorWithColor在上下文中設置筆觸顏色。當您沿着路徑行進時使用該顏色,在繼續構建路徑時它不起作用。

您需要分別對每條線進行筆劃(CGContextStrokePath)。

+0

謝謝你,我通過 – 2010-10-26 12:50:44

+0

調用這個 - (空)drawLayer:(CALayer的*)層inContext的:(CGContextRef)CTX { – 2010-10-26 12:51:19

+0

那麼這將會使我的任何問題?我將如何創建另一個上下文? – 2010-10-26 12:52:11