这两张图最能说明问题。第一张图片显示了一个尚未悬停的 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
最佳答案
绘图系统将需要重绘的 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/