2011-06-05 66 views
0

下面的代碼應該在mapWindow NSView上繪製一個矩形。我的程序還有另一個使用NSView窗口的文件;爲什麼我想要一個新窗口。但是,矩形不顯示。任何幫助,將不勝感激。Objective-C在單獨的窗口上繪圖

@interface mapWindow : NSView {@private NSView* theMapWindow;} 

- (void)drawRect:(int)pointx: (int)pointy; 

@property (assign) IBOutlet NSView* theMapWindow; 

@end 

@implementation mapWindow 
@synthesize theMapWindow; 
- (void)mouseDown:(NSEvent *)event 
{ 
    NSPoint point = [event locationInWindow]; 
    //NSLog(@"mouseDown location: (%f,%f)", (float) point.x, (float) point.y); 
    [self drawRect:point.x:point.y]; 
} 

- (void)drawRect:(int)pointx: (int)pointy 
{ 
    NSLog(@"Drawing point at (%d, %d)",pointx, pointy); 
    NSPoint origin = { pointx,pointy }; 

    NSRect rect; 
    rect.origin = origin; 
    rect.size.width = 128; 
    rect.size.height = 128; 

    NSBezierPath * path; 
    path = [NSBezierPath bezierPathWithRect:rect]; 

    [path setLineWidth:4]; 

    [[NSColor whiteColor] set]; 
    [path fill]; 

    [[NSColor grayColor] set]; 
    [path stroke]; 

    [theMapWindow setNeedsDisplayInRect:rect]; 
} 

回答

1

NSViewdrawRect:方法以您的名義;您應該將其用於您的圖紙,如Drawing View Content中所述。

@interface mapWindow : NSView { 

@private 
    NSView* theMapWindow; 
    NSPoint drawPoint; 
} 

// - (void)drawRect:(int)pointx: (int)pointy; 

@property (assign) IBOutlet NSView* theMapWindow; 
@property (assign) NSPoint drawPoint; 

@end 

-

@implementation mapWindow 

@synthesize theMapWindow, drawPoint; 

- (void)mouseDown:(NSEvent *)event 
{ 
    NSPoint point = [event locationInWindow]; 
    NSLog(@"[%@ %@] mouseDown location == %@", 
       NSStringFromClass([self class]), 
       NSStringFromSelector(_cmd), 
       NSStringFromPoint(point)); 

    [self setDrawPoint:point]; 

    [self setNeedsDisplay:YES]; 

    //NSLog(@"mouseDown location: (%f,%f)", (float) point.x, (float) point.y); 
    //[self drawRect:point.x:point.y]; 
} 

- (void)drawRect:(NSRect)frame { 
    NSLog(@"Drawing point at %@", NSStringFromPoint(drawPoint)); 
    NSRect drawFrame = NSMakeRect(point.x, point.y, 128.0, 128.0); 
    [NSBezierPath setDefaultLineWidth:4]; 
    [[NSColor whiteColor] set]; 
    [NSBezierPath fillRect:drawFrame]; 
    [[NSColor grayColor] set]; 
    [NSBezierPath strokeRect:drawFrame]; 
} 
+0

point.x和point.y不能被調用,因爲它們不存在。 – evdude100 2011-06-05 13:26:37

+0

但我做了類似的事情,謝謝!我用NSPoint origin = [self drawPoint]; – evdude100 2011-06-05 13:53:47

2

你做錯了。你不應該自己打電話drawRect,它會被要求你。將drawRect的呼叫替換爲setNeedsDisplayInRect,並從drawRect方法中刪除setNeedsDisplayInRect

+0

這樣做並沒有任何影響。 – evdude100 2011-06-05 03:11:42

+0

編輯爲更好的解決方案 – Dani 2011-06-05 03:12:42

+0

換句話說: - (void)setNeedsDisplayInRect:(int)pointx:(int)pointy {insert ..}? – evdude100 2011-06-05 03:14:36

1

您的drawRect ::是自定義方法,與drawRect不同:當您將視圖作爲當前上下文時,將不會調用它,請嘗試在您的繪圖代碼周圍放置[self lockFocus][self unlockFocus]

+0

謝謝你讓我知道,而是我要使它成爲一種內置的方法。 – evdude100 2011-06-05 13:48:51