objective-c - NSView drawRect 干扰 NSButton 悬停

标签 objective-c xcode cocoa nsview nsbutton

这两张图最能说明问题。第一张图片显示了一个尚未悬停的 nsbutton,第二张图片显示了当我将鼠标悬停在其上时相同的 nsbutton。

正如您所看到的,无论出于何种原因,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

最佳答案

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

您应该测试 rect 以确保它适合用于路径,或者 - 更容易且很好,除非您遇到可测量的与绘图相关的性能问题 - 始终使用轮廓路径的 View 边界。

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

绘图上下文无论如何都会将绘图剪切到它所要求的矩形。

关于objective-c - NSView drawRect 干扰 NSButton 悬停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165757/

相关文章:

ios - NSXML Parser 跳过 & In 字符串后的剩余字符串

ios - MPMoviePlayerController 从第 30 秒开始播放视频(从视频中间开始)

objective-c - 我如何判断一个对象是否附加了键值观察器

iphone - 单击链接时如何发送电子邮件?

ios - 如何在 IOS 项目的 viewController 中向 flutterViewController 添加边距/填充

xcode - 是否可以编写移动 Safari 扩展程序?

ios - XCode 中的 ObjC 链接器标志

objective-c - 强制 'Shared User Defaults Controller'立即保存到磁盘?

ios - 如何检查 uiimage 是否为空白? (空的,透明的)

objective-c - 使用 Cocoa 在 HDD 上下载并保存图像文件