1. 懒加载渐变涂层
private lazy var subLayer: CAGradientLayer = {
let layer = CAGradientLayer()
// 设置从什么颜色开始
let fromColor = UIColor.red
// 设置以什么颜色结束
let toColor = UIColor.black
let colors = [fromColor, toColor].map { $0.cgColor }
//设置开始和结束位置(设置渐变的方向)
layer.startPoint = CGPoint(x: 0, y: 0);
layer.endPoint = CGPoint(x: 0, y: 1);
layer.colors = colors;
return layer
}()
2. layer添加渐变涂层
self.layer.addSublayer(subLayer)
3. 设置渐变涂层frame
override func layoutSubviews() {
super.layoutSubviews()
subLayer.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height);
}
网友评论