带有圆角和背景色的NSButton [英] NSButton with round corners and background color
问题描述
我想要一个简单的按钮(带有圆角的按钮),并为其添加背景. 我已经尝试了两件事:
I want a simple push button (the one with the round corners), and to add background to it. I've tried 2 things:
1-使用圆形按钮图像:这很好,直到我需要缩放按钮为止,这会导致圆形部分看起来难看.
1 - using a round button image: this is working good, until I need to scale the button, which cause the round parts to look ugly.
2-扩展按钮并为其添加颜色-但是单击按钮时遇到麻烦-我希望按动"状态与常规"状态具有相同的颜色,但事实并非如此
2 - extending the button and add color to it - but then I have trouble when I click the button - I want the "pushed" state to be at the same color as the "regular" state, but it's not the case.
这是我用来扩展按钮的代码:
this is the code I'm using to extend the button:
override func drawRect(dirtyRect: NSRect)
{
if let bgColor = bgColor {
self.layer?.cornerRadius = 4
self.layer?.masksToBounds = true
self.layer?.backgroundColor = bgColor.CGColor
bgColor.setFill()
NSRectFill(dirtyRect)
}
super.drawRect(dirtyRect)
}
无论如何,方法1和2都不起作用,那么如何实现呢? 只是一个简单的按钮..:(
Anyway, neither approach 1 nor 2 worked, so how can I achieve this ? Just a simple button.. :(
我在问OSX
推荐答案
我做了一个按钮,就成功了.看起来像这样:
I made a button and succeeded. It looks like this:
代码:
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
if let bgColor = bgColor {
self.layer?.cornerRadius = 4
self.layer?.masksToBounds = true
self.layer?.backgroundColor = bgColor.cgColor
bgColor.setFill()
NSRectFill(dirtyRect)
}
}
drawRect替换为draw,而CGColor替换为cgColor.您和我的区别在于订单.您最后一次调用了super.draw(dirtyRect)
,而我首先调用了它.也许您的按钮看起来像这样:
drawRect is replaced by draw, and CGColor is replaced by cgColor. The difference between yours and mine is the order. You called super.draw(dirtyRect)
as last, and I called it first. Maybe your button looks like this:
我希望这可以解决您的问题.
I hope this can solve your problem.
这篇关于带有圆角和背景色的NSButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!