NSView drawRect干扰NSButton悬停

时间:2013-03-01 19:53:04

标签: objective-c xcode cocoa nsview nsbutton

这两张照片最好解释一下。第一张图片显示的是尚未悬停的ns按钮,第二张图片显示的是当我悬停在它上面时相同的ns按钮。

正如您所看到的,无论出于何种原因,NSView外部贝塞尔曲线路径似乎也会在按钮上绘制。该按钮是普通的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

1 个答案:

答案 0 :(得分:4)

绘图系统将需要重新绘制的视图的矩形作为单个参数传递给drawRect:您无条件地使用该矩形作为路径path = [NSBezierPath bezierPathWithRect:rect];,假设此矩形是始终是视图的完整边界rect。不是这种情况。当按钮悬停在其上时,其框架是视图中已失效且需要重新绘制的部分,这就是rect的内容。

你应该测试rect以确保它适合用于路径,或者 - 更简单,更好,除非你有可衡量的与绘图相关的性能问题 - 总是使用视图的界限大纲路径。

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

绘图上下文会将绘图剪切到它要求的矩形。

相关问题