2011-10-27 31 views
3

我用下面的代碼來畫虛線如何讓虛線動

// get the current CGContextRef for the view 
    CGContextRef currentContext = 
    (CGContextRef)[[NSGraphicsContext currentContext] 
    graphicsPort]; 

    // grab some useful view size numbers 
    NSRect bounds = [self bounds]; 
    float width = NSWidth(bounds); 
    float height = NSHeight(bounds); 
    float originX = NSMinX(bounds); 
    float originY = NSMinY(bounds); 
    float maxX = NSMaxX(bounds); 
    float maxY = NSMaxY(bounds); 
    float middleX = NSMidX(bounds); 
    float middleY = NSMidY(bounds); 

    CGContextSetLineWidth(currentContext, 10.0); 
    float dashPhase = 0.0; 
    float dashLengths[] = { 20, 30, 40, 30, 20, 10 }; 
    CGContextSetLineDash(currentContext, 
     dashPhase, dashLengths, 
     sizeof(dashLengths)/sizeof(float)); 

    CGContextMoveToPoint(currentContext, 
     originX + 10, middleY); 
    CGContextAddLineToPoint(currentContext, 
     maxX - 10, middleY); 
    CGContextStrokePath(currentContext); 

enter image description here

它是靜態的。

但我更喜歡做活動的虛線和間隙

移動由右至左和圈

這可能嗎?

進一步改善的情況:

enter image description here

虛線和間隙順時針移動自動

歡迎任何評論

+0

真棒問題。我希望早晚實現到我的代碼中的東西只是不知道如何。 +1 –

回答

2

最簡單的方法是使phase變量伊娃並覆蓋keyDown:

- (BOOL)acceptsFirstResponder 
{ 
    return YES; 
} 

- (void)keyDown:(NSEvent *)theEvent 
{ 
    switch ([theEvent keyCode]) 
    { 
     case 0x7B: //left cursor key 
      dashPhase += 10.0; 
      break; 
     case 0x7C: //right cursor key 
      dashPhase -= 10.0; 
      break; 
     default: 
      [super keyDown:theEvent];    
      break; 
    } 
    [self setNeedsDisplay:YES]; 
} 

還請確保將窗口的initialResponder設置爲自定義視圖(我假設您在NSView子類中執行繪圖)。

包裝代碼不應該太難。只需劃分你的dashLengths陣列並按照你想要的方式重新組裝。 (您如果要分割單短線與否沒有指定)

更新

確定。我誤解了你的問題中的「從右向左移動並圈出」部分內容。我以爲你想要虛線纏繞。如果你想繪製一個可移動,虛線的邊框,甚至會更容易。把它放在一個NSView子類中,當你按←或者→時,它應該繪製一個虛線的矩形來移動它的破折號:

- (id)initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     patternRectangle = [self bounds]; 
    } 

    return self; 
} 

- (void)drawRect:(NSRect)dirtyRect 
{ 
    CGContextRef currentContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort]; 
    CGContextSetLineWidth(currentContext, 10.0); 
    CGFloat dashLengths[] = { 20, 30, 40, 30, 20, 10 }; 
    CGContextSetLineDash(currentContext, dashPhase, dashLengths, sizeof(dashLengths)/sizeof(float)); 
    CGPathCreateWithRect(CGRectMake(2.0, 2.0, 100.0, 100.0), NULL); 
    CGContextStrokeRect(currentContext, CGRectInset(NSRectToCGRect([self bounds]), 10.0, 10.0)); 
    CGContextStrokePath(currentContext); 
} 

- (BOOL)acceptsFirstResponder 
{ 
    return YES; 
} 

- (void)keyDown:(NSEvent *)theEvent 
{ 
    switch ([theEvent keyCode]) 
    { 
     case 0x7B: 
      dashPhase += 10.0; 
      break; 
     case 0x7C: 
      dashPhase -= 10.0; 
      break; 
     default: 
      [super keyDown:theEvent];    
      break; 
    } 
    [self setNeedsDisplay:YES]; 
} 
+0

我希望破折號和間隙自動移動,請參考虛擬化問題 – monsabre