试试这个:
@IBOutlet weak var loginButton: UIButton!
func testGradientButton() -> Void {
let gradientColor = CAGradientLayer()
gradientColor.frame = loginButton.frame
gradientColor.colors = [UIColor.blue.cgColor,UIColor.red.withAlphaComponent(1).cgColor]
self.loginButton.layer.insertSublayer(gradientColor, at: 0)
}
这是结果:
![enter image description here](https://istack.dev59.com/BBpJ6.webp)
另外请注意:您代码中RGB颜色的值远高于其正常值。请查看控制台日志,可能会打印以下错误:
[Graphics] UIColor创建时组件值远超出预期范围。设置一个断点在UIColorBreakForOutOfRangeColorComponents上进行调试。此消息仅记录一次。
将所有值除以255.0并使用
insertSubLayer
函数。
let color1 = UIColor(red: 183.0/255.0, green: 46.0/255.0, blue: 79.0/255.0, alpha: 1)
let color2 = UIColor(red: 232.0/255.0, green: 79.0/255.0, blue: 80.0/255.0, alpha: 1)
let color3 = UIColor(red: 145.0/255.0, green: 21.0/255.0, blue: 79.0/255.0, alpha: 1)
这里是您颜色代码值的结果:
func testGradientButton() -> Void {
let gradientColor = CAGradientLayer()
gradientColor.frame = loginButton.frame
let color1 = UIColor(red: 183.0/255.0, green: 46.0/255.0, blue: 79.0/255.0, alpha: 1)
let color2 = UIColor(red: 232.0/255.0, green: 79.0/255.0, blue: 80.0/255.0, alpha: 1)
let color3 = UIColor(red: 145.0/255.0, green: 21.0/255.0, blue: 79.0/255.0, alpha: 1)
gradientColor.colors = [color1.cgColor,color2.cgColor,color3.cgColor]
self.loginButton.layer.insertSublayer(gradientColor, at: 0)
}
![enter image description here](https://istack.dev59.com/Q8lg4.webp)
gradientColor.frame = loginButton.frame
你可能想要使用gradientColor.frame = loginButton.bounds
。同时,UIColor(red:green:blue:alpha:)
的值需在0和1之间。因此,可以使用UIColor(red: 183/255., green: 46/255., blue: 79/255., alpha: 1)
(对于每种颜色都是如此)。 - LarmegradientColor.colors
需要是一个CGColor
数组:https://dev59.com/1GAf5IYBdhLWcg3wsUXT - LarmeloginButton.frame
的框架是什么?可能是自动布局问题。 - Larme