【问题标题】:NSView drawRect interfering with NSButton hoverNSView drawRect 干扰 NSButton 悬停
【发布时间】:2013-02-16 10:16:09
【问题描述】:

这两张图最好的解释。第一张图片显示了一个尚未悬停的 nsbutton,第二张显示了当我将鼠标悬停在它上面时相同的 nsbutton。

如您所见,无论出于何种原因,NSView 外部贝塞尔路径似乎也绘制在按钮上。按钮是一个普通的 NSButton 实例,没有子类。

这是我的自定义 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

【问题讨论】:

    标签: objective-c xcode cocoa nsview nsbutton


    【解决方案1】:

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

    您应该测试 rect 以确保它适合用于路径,或者 -- 更简单也很好,除非您遇到与绘图相关的性能问题 -- 始终使用视图的边界作为轮廓路径。

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

    绘图上下文将把绘图剪辑到它要求的矩形。

    【讨论】:

    • 啊,太好了,感谢您的解释。如果我理解正确,我还可以检查传递的矩形是否与边界大小相同,如果不是,那么我根本不需要做任何绘图。 (然后是悬停的按钮或其他东西)。
    • 不,在这种特殊情况下,您需要重新绘制白色背景 - 按钮也会在其椭圆形之外绘制,但在其框架内。
    • 哦,是的,因为它是透明的边缘。感谢您的清晰解释。
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 2017-05-12
    • 2016-07-28
    • 1970-01-01
    • 2014-05-11
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多