2013-03-01 36 views
2

最好由這兩張圖片來解釋。第一張圖顯示了一個尚未被徘徊的nsbutton,第二張顯示了當我將它懸停時的nsbutton。NSView drawRect干擾NSButton懸停

正如你所看到的,NSView外部bezier路徑似乎也被繪製在按鈕上,無論出於何種原因。該按鈕是一個普通的NSButton實例,不是子類。

enter image description here

enter image description here

這裏是我的自定義的NSView:

#import "MyView.h" 

@implementation MyView 
- (void)drawRect:(NSRect)rect 
{  
    NSBezierPath *path; 

    path = [NSBezierPath bezierPathWithRect:rect]; 
    [[NSColor redColor] set]; 
    [path fill]; 

    rect.size.width -= 10; 
    rect.size.height -= 10; 
    rect.origin.x += 5; 
    rect.origin.y += 5; 

    path = [NSBezierPath bezierPathWithRect:rect]; 
    [[NSColor whiteColor] set]; 
    [path fill]; 
} 

- (void)awakeFromNib 
{ 
    NSButton *commandButton = [[NSButton alloc] initWithFrame:NSMakeRect(90, 50, 100, 18)]; 

    [commandButton setButtonType:NSMomentaryPushInButton]; 
    [commandButton setBordered:YES]; 
    [commandButton setTitle:@"Test!"]; 
    [commandButton setFont:[NSFont fontWithName:@"LucidaGrande" size:14.0]]; 
    [commandButton setBezelStyle:NSInlineBezelStyle]; 

    [self addSubview:commandButton]; 
} 

@end 

回答

4

繪圖系統通過在需要重畫爲單個參數drawRect:你的觀點的矩形假設這個矩形總是視圖的全部邊界矩形,則無條件地使用該矩形作爲路徑path = [NSBezierPath bezierPathWithRect:rect];。不是這種情況。當按鈕懸停時,其框架是您視圖中已被無效且需要重繪的部分,這就是rect

您應該測試rect以確定它適合用於路徑,或者 - 除非您具有可測量的與繪圖相關的性能問題,否則更容易和更好 - 始終使用視圖的輪廓路徑邊界。

path = [NSBezierPath bezierPathWithRect:[self bounds]]; 

繪圖上下文會將繪圖剪切到它要求的矩形。

+0

很好,謝謝你的解釋。如果我理解正確的話,我也可以檢查通過的rect是否與邊界相同,如果不是,那麼我根本不需要做任何繪圖。 (然後它是一個按鈕被徘徊或別的東西)。 – Wesley 2013-03-01 20:29:12

+0

不,在這種特殊情況下,您需要重新繪製該白色背景 - 該按鈕也會在其外框內繪製橢圓,但在其框架內。 – 2013-03-01 20:35:51

+0

哦,是的,因爲它是透明的邊緣。謝謝你的明確解釋。 – Wesley 2013-03-01 20:39:41