1。创建 渐变色
/// 渐变色:默认从上到下 private var gradientLayer: CAGradientLayer = { let g = CAGradientLayer() g.colors = [UIColor.init(hexColor: "DBB479").cgColor, UIColor.init(hexColor: "F7E1B3").cgColor] //改为从左到右 的渐变 g.startPoint = CGPoint(x: 0, y: 0) g.endPoint = CGPoint(x: 1, y: 0) return g }()
2.给指定view 添加渐变色
/// 荣誉背景图 private lazy var credibilityBgView : UIView = { let v = UIView() v.layer.addSublayer(self.gradientLayer) v.translatesAutoresizingMaskIntoConstraints = false v.layer.cornerRadius = 5 v.layer.masksToBounds = true v.isUserInteractionEnabled = true v.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clcikCredibilityBgView))) return v }()
3. 设置 渐变色frame
override func draw(_ rect: CGRect) { super.draw(rect) gradientLayer.frame = credibilityBgView.bounds }