在UIButton的背景上添加一个渐变图层
问题描述:
我有一个项目,它包含了一些UIStackView中的按钮。每个按钮都有一个backgroundImage。一切都按照需要进行渲染,但是我想在背景图像的前面放置一个半透明的渐变图层,以便按钮上的文本具有更多的对比度。在UIButton的背景上添加一个渐变图层
我试图用这个代码viewDidLoad
,在每个的UIButton的将backgroundImage前加上一个半透明渐变:
buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5)]
// gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.5).cgColor]
// gradientLayer.colors = [UIColor.orange]
// gradientLayer.colors = [UIColor.orange.cgColor]
buttonArray.forEach({$0.imageView?.layer.insertSublayer(gradientLayer, at: 0)})
因为它的立场,没有被添加。我尝试将颜色更改为没有alpha值的颜色,并将所需的颜色更改为.cgColor。没有骰子。谢谢你的阅读。我欢迎你的建议,如何在UIButton的backgroundImage前放置一个gradientLayer。
我根据我尝试过的代码中发现here
答
我认为你必须指定一个以上的颜色,还有层的界限:
let buttonArray = [buttonOne, buttonTwo, buttonThree, buttonFour]
for button in buttonArray {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor(white: 0.5, alpha: 0.5).cgColor, UIColor(white: 1.0, alpha: 0.5).cgColor]
gradientLayer.frame = (button?.bounds)!
button?.layer.insertSublayer(gradientLayer, at: 0)
}
+0
谢谢你的阅读。这对我没有用。 – Adrian
有你试图添加层图像,然后你分配这个图像作为你的背景图像? – antonio081014
好主意。我会给它一个旋转 – Adrian