【Swift】CAGradientLayer 实现渐变色效果

2020-03-20  本文已影响0人  BeethOven

在项目中的渐变色控件我继承自我的RLGrandientLayerView,实现
Demo如图


渐变色.gif

源码:

class RLGrandientLayerView: UIView {
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }
    
    var gradientColors: [UIColor]?
    
    var locations: [NSNumber]?
    
    var startPoint: CGPoint = .zero
    
    var endPoint: CGPoint = CGPoint.init(x: 1, y: 1)
    
    required convenience init(grandientColors: [UIColor]) {
        self.init(frame: .zero)
        self.gradientColors = grandientColors
        locations = [0.0, 1.0]
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let layer = layer as? CAGradientLayer {
            layer.colors = gradientColors?.map({ $0.cgColor })
            layer.locations = locations
            layer.startPoint = startPoint
            layer.endPoint = endPoint
        }
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读