将水平渐变添加到边线

时间:2016-10-15 14:29:21

标签: swift

我在视图中创建了简单的边框。但是我正在努力为它提供水平渐变背景颜色。我该怎么办?

我试过这样,但它只是将颜色设置为白色:

    let border = CAGradientLayer()
    border.frame = CGRect(x: 0, y: self.mainView.frame.height - 2, width: self.mainView.frame.width, height: 2)
    border.backgroundColor = UIColor.gray.cgColor
    let color1 = UIColor.black.withAlphaComponent(0.1).cgColor as CGColor
    let color2 = UIColor.white.withAlphaComponent(0.9).cgColor as CGColor
    border.locations = [0.60, 1.0]// Are these right coordinates?
    border.colors = [color2, color1]

1 个答案:

答案 0 :(得分:6)

我得到了这样的工作:

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: self.mainView.frame.height - 2, width: self.mainView.frame.width, height: 2)
gradientLayer.colors =  [UIColor.green,UIColor.blue ].map{$0.cgColor}
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

我不得不使用CALayer(),而是使用CAGradientLayer()