1. 程式人生 > >Swift新增CAGradientLayer漸變色背景顏色

Swift新增CAGradientLayer漸變色背景顏色

漸變色的簡單實現

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.view.bounds
gradientLayer.colors = [UIColor(hex: "ffffff").cgColor, UIColor(hex: "000000").cgColor]
view.layer.addSublayer(gradientLayer)

寫成擴充套件的自定義方法

import UIKit

extension UIView {
    
    public func addGradientLayer(
        start: CGPoint = CGPoint(x: 0, y: 0), //漸變起點
        end: CGPoint = CGPoint(x: 1, y: 1), //漸變終點
        frame: CGRect,
        colors: [CGColor]
    ) {
        layoutIfNeeded()
        removeGradientLayer()
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = start
        gradientLayer.endPoint = end
        gradientLayer.frame = frame
        gradientLayer.colors = colors
        layer.insertSublayer(gradientLayer, at: 0)
    }
    
    public func removeGradientLayer() {
        guard let layers = self.layer.sublayers else { return }
        for layer in layers {
            if layer.isKind(of: CAGradientLayer.self) {
                layer.removeFromSuperlayer()
            }
        }
    }
    
}

使用

view.addGradientLayer(frame: view.bounds, colors: [UIColor(hex: "ffffff").cgColor, UIColor(hex: "000000").cgColor])