具有半透明背景的自定义 NSButton

发布于 2024-12-23 04:18:06 字数 577 浏览 4 评论 0原文

我正在尝试创建一个具有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦幻之岛 2024-12-30 04:18:06

NSRectFill() 的默认操作是 copy 这不是你想要的。将其替换为

NSRectFillUsingOperation(dirtyRect, NSCompositeSourceAtop);

The default operation of NSRectFill() is copy which is not what you want. Replace it with

NSRectFillUsingOperation(dirtyRect, NSCompositeSourceAtop);
∞琼窗梦回ˉ 2024-12-30 04:18:06

我发现的另一个解决方案是保持代码相同,但在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文