我有一个按钮,我正在尝试设置其背景颜色渐变。我有三个十六进制值,我转换为RGB并在我的代码中写入三个值,并将所有三个值传递给按钮帧。但是,当我运行应用程序按钮时,背景不会根据我在代码中设置的颜色而改变。获取三种颜色代码的代码就是这个,
let gradientColor = CAGradientLayer()
gradientColor.frame = loginButton.frame
let color1 = UIColor(red: 183, green: 46, blue: 79, alpha: 1)
let color2 = UIColor(red: 232, green: 79, blue: 80, alpha: 1)
let color3 = UIColor(red: 145, green: 21, blue: 79, alpha: 1)
gradientColor.colors = [color1,color2,color3]
self.loginButton.layer.addSublayer(gradientColor)
答案 0 :(得分:0)
试试这个,看看:
@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)
}
结果如下:
另请注意:代码中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)
}