随着ios 12和swift 4.2的推出,我的代码不再适用了。它曾经是一个从左到右,深紫色到浅紫色按钮的渐变。我怎样才能解决这个问题?
// Gives the button gradient values
func setGradientButton(colorOne: UIColor, colorTwo: UIColor, x1: Double, y1: Double, x2: Double, y2: Double) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 0.0]
gradientLayer.startPoint = CGPoint(x: x1, y: y1)
gradientLayer.endPoint = CGPoint(x: x2, y: y2)
layer.insertSublayer(gradientLayer, at: 0)
}
// Sets UI elements
func setUI(_ label : UILabel, _ button : UIButton) {
let colorOne = UIColor(red: 119.0 / 255.0, green: 85.0 / 255.0, blue: 254.0 / 255.0, alpha: 100.0)
let colorTwo = UIColor(red: 177.0 / 255.0, green: 166.0 / 255.0, blue: 251.0 / 255.0, alpha: 100.0)
button.setGradientButton(colorOne: colorOne, colorTwo: colorTwo, x1: 0.0, y1: 50, x2: 150, y2: 50)
button.layer.cornerRadius = 4
button.clipsToBounds = true
}
我不能假设你的代码之前为什么有效,但我发现你的CAGradientLayer
设置有一些问题。
起初,locations
阵列。根据Apple Documentation,这个值“定义了每个梯度停留的位置”。因此,如果您希望渐变以一种颜色开始并以另一种颜色结束,则需要将locations
设置为
gradientLayer.locations = [0.0, 1.0]
另一个问题是startPoint
和endPoint
。再次,来自documentation:
该点在单位坐标空间中定义,然后在绘制时映射到图层的边界矩形。
所以你的积分值应该在0.0
和1.0
之间。在单位坐标空间中,(0.0, 0.0)
是视图的左上角,(1.0, 1.0)
是右下角。如果你想得到一个水平渐变,你需要设置这样的点
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
希望它能帮到你。