2012-10-29 83 views
0

我想繪製一個簡單的圖。我有用線連接的正方形。這些線條用NSBezierPath's繪製。我使用隨機顏色的線條,所以我可以跟着他們。我的問題是線條改變顏色。在NSBezierPath上剝離的筆劃

輸出 -

enter image description here

代碼 - 我刪除畫正方形的線,所以它只能繪製線:

- (void)drawRect:(NSRect)dirtyRect 
{ 
    // Drawing code here. 
    [[NSColor whiteColor] setFill]; 
    NSRectFill(dirtyRect); 

    CGFloat height = 70.0f; 
    CGFloat yOffset = 20.0f; 

    NSRect rect = NSMakeRect(50.0f, 50.0f, 200.0f, height); 

    NSEnumerator *reverseEnumerator = [steps reverseObjectEnumerator]; 

    NSMutableDictionary *rectsByStep = [NSMutableDictionary dictionaryWithCapacity:10]; 

    for(WFGJobStep *step in reverseEnumerator) 
    { 
     [[NSColor redColor] setFill]; 


     [rectsByStep setObject:[NSValue valueWithRect:rect] forKey:[NSNumber numberWithInteger:step.step]]; 

     rect.origin.y += height + yOffset; 

    } 

    reverseEnumerator = [steps reverseObjectEnumerator]; 
    for(WFGJobStep *step in reverseEnumerator) 
    { 
     NSRect stepRect = [[rectsByStep objectForKey:[NSNumber numberWithInteger:step.step]] rectValue]; 
     NSPoint startPoint = NSMakePoint(stepRect.origin.x + stepRect.size.width, stepRect.origin.y); 

     // draw lines 
     for(NSNumber *stepNumber in step.nextSteps) 
     { 

     // 
     // 
     // Line drawing code here 
     // 
     // 

      NSBezierPath * path = [NSBezierPath bezierPath]; 
      [path setLineWidth: 4]; 

      NSRect targetStepRect = [[rectsByStep objectForKey:stepNumber] rectValue]; 
      NSPoint endPoint = NSMakePoint(targetStepRect.origin.x + targetStepRect.size.width, targetStepRect.origin.y + targetStepRect.size.height); 

      [path moveToPoint:startPoint]; 

      CGFloat controlX = (startPoint.y - endPoint.y) * .2 + stepRect.origin.x + stepRect.size.width + 20; 

      [path curveToPoint:endPoint controlPoint1:NSMakePoint(controlX, startPoint.y) controlPoint2:NSMakePoint(controlX, endPoint.y)]; 

      NSRect square = NSMakeRect(endPoint.x, endPoint.y, 9, 9); 
      [path appendBezierPathWithOvalInRect: square]; 

      [[self randomColor] set]; 
      [path stroke]; 
     } 
    } 
} 

- (NSColor *)randomColor { 
    float c[4]; 

    c[0] = (arc4random()/RAND_MAX) * 1; 
    c[1] = (arc4random()/RAND_MAX) * 1; 
    c[2] = (arc4random()/RAND_MAX) * 1; 
    c[3] = 1.0f; 

    return [NSColor colorWithDeviceRed:c[0] green:c[1] blue:c[2] alpha:c[3]]; 
} 
+0

該死的 - 很確定在基本的WWDC可可圖形會話中有類似的東西,但是無法追蹤相關的會話..你是否將'NSView'標記爲不透明? – Jay

+0

我試着重寫方法isOpaque並返回YES。同樣的結果。 – Brian

回答

2

我的問題是,這是一個scoll視圖這是我的第一個NSScrollView。我沒有意識到,當視圖滾動它重繪其子視圖。問題在於我爲我的筆畫使用了隨機顏色,因此當我滾動它時,會隨機更改線條的顏色。