具有半透明背景的自定义 NSButton
我正在尝试创建一个具有 50% 不透明黑色背景和白色文本的自定义 NSButton。为此,我对 NSButton 进行了子类化并重载了 DrawRect:
- (void) drawRect:(NSRect)dirtyRect
{
[self setBordered:NO];
//REMED since it has same effect as NSRectFill below
//[[self cell] setBackgroundColor:[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.2]];
NSColor* backgroundColor = [NSColor colorWithCalibratedWhite:0 alpha:0.3f];
[backgroundColor setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
白色文本看起来很好,但按钮的背景始终是 100% 不透明。不解释 alpha 值。
有什么想法吗?谢谢!
I'm trying to create a custom NSButton with a 50% opaque black background and white text. To do this I've subclassed NSButton and overloaded DrawRect:
- (void) drawRect:(NSRect)dirtyRect
{
[self setBordered:NO];
//REMED since it has same effect as NSRectFill below
//[[self cell] setBackgroundColor:[NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.2]];
NSColor* backgroundColor = [NSColor colorWithCalibratedWhite:0 alpha:0.3f];
[backgroundColor setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
The white text appears fine but the button's background is always 100% opaque. The alpha value is not interpreted.
Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSRectFill()
的默认操作是 copy 这不是你想要的。将其替换为The default operation of
NSRectFill()
is copy which is not what you want. Replace it with我发现的另一个解决方案是保持代码相同,但在 Interface Builder 中为每个按钮打开核心动画层。我对核心动画层了解不够,不知道为什么它会起作用。我之前关闭了 CAL,因为它使我的字体看起来非常锯齿。
Another solution I found was to keep my code the same but turn on the Core Animation Layer for each button in Interface Builder. I don't know enough about Core Animation Layer to know why this worked. I had previously turned CAL off because it was making my fonts look very jagged.