直接代码记录
/// 渐变色view, 带有渐变效果的View, 方便调用
class LZGradientView: UIView {
private(set) var colors: [CGColor] = []
private(set) var direction: BBGradientColorDirection = .topToBottom
public func setColors( colors: [CGColor],
direction: BBGradientColorDirection = .topToBottom) {
self.direction = direction
self.colors = colors
self.setGradientLayer()
}
func setGradientLayer() {
// add layer
let gradientLayer = self.layer as? CAGradientLayer //重要 直接用 self.layer
gradientLayer?.colors = self.colors
// locations
// gradientLayer?.locations = [0, 1]
// start, end point
switch direction {
case .topToBottom:
gradientLayer?.startPoint = CGPoint(x: 0, y: 0)
gradientLayer?.endPoint = CGPoint(x: 0, y: 1)
case .bottomToTop:
gradientLayer?.startPoint = CGPoint(x: 0, y: 1)
gradientLayer?.endPoint = CGPoint(x: 0, y: 0)
case .leftToRight:
gradientLayer?.startPoint = CGPoint(x: 0, y: 0)
gradientLayer?.endPoint = CGPoint(x: 1, y: 0)
case .rightToLeft:
gradientLayer?.startPoint = CGPoint(x: 1, y: 0)
gradientLayer?.endPoint = CGPoint(x: 0, y: 0)
case .rightTopToLeftBottom:
gradientLayer?.startPoint = CGPoint(x: 1, y: 0)
gradientLayer?.endPoint = CGPoint(x: 0, y: 1)
case .leftTopToRightBottom:
gradientLayer?.startPoint = CGPoint(x: 0, y: 0)
gradientLayer?.endPoint = CGPoint(x: 1, y: 1)
}
}
}