2011-02-09 17 views
2

指南針的每個點我的圈子的外邊緣被裁剪(大概是由矩形框架)。我如何讓圓圈在框架內顯示? (這正從一個按鈕,點擊創建):可可NSView:製作圈子,但他們正在裁剪

在我AppController.m

#import "AppController.h" 
#import "MakeCircle.h" 

@implementation AppController 

- (IBAction)makeCircle:(id)sender { 

    MakeCircle* newCircle = [[MakeCircle alloc] initWithFrame:NSMakeRect(100.0, 100.0, 30.0, 30.0)]; 
    [[[[NSApplication sharedApplication] mainWindow] contentView] addSubview:newCircle]; 

    [newCircle release]; 
} 

@end 

在我MakeCircle.m

- (void)drawRect:(NSRect)rect { 

    [self setNeedsDisplay:YES]; 

    [[NSColor blackColor] setStroke]; 

    // Create our circle path 
    NSBezierPath* circlePath = [NSBezierPath bezierPath]; 
    [circlePath appendBezierPathWithOvalInRect: rect]; 

    //give the line some thickness 
    [circlePath setLineWidth:4]; 

    // Outline and fill the path 
    [circlePath stroke]; 


    } 

感謝。

回答

6

我想你只看到一半的邊緣,對吧?你可以計算出邊緣的厚度的一半,減去從矩形:

#define STROKE_COLOR ([NSColor blackColor]) 
#define STROKE_WIDTH (4.0) 
- (void)drawRect:(NSRect)dirtyRect { 
    NSBezierPath *path; 
    NSRect rectangle; 

    /* Calculate rectangle */ 
    rectangle = [self bounds]; 
    rectangle.origin.x += STROKE_WIDTH/2.0; 
    rectangle.origin.y += STROKE_WIDTH/2.0; 
    rectangle.size.width -= STROKE_WIDTH/2.0; 
    rectangle.size.height -= STROKE_WIDTH/2.0; 
    path = [NSBezierPath path]; 
    [path appendBezierPathWithOvalInRect:rectangle]; 
    [path setLineWidth:STROKE_WIDTH]; 
    [STROKE_COLOR setStroke]; 
    [path stroke]; 
} 

我有沒有蘋果的那一刻,所以我不能測試它,但我認爲它應該解決您的問題。

Als不叫[self setNeedsDisplay:YES]。當你想重繪你的整個NSView時使用該方法,並且從繪圖方法調用它是有點遞歸的。這就是爲什麼我驚訝你的代碼實際上吸引了一些東西。

而我有另外一個提示:[[NSApplication sharedApplication] mainWindow]實際上和[NSApp mainWindow]一樣。 NSApp是包含主應用程序的全局變量。

希望它能幫助,
ief2

+4

`NSInsetRect`將通過3線縮短了代碼。 – Richard 2011-02-09 15:46:04