Swift5 UIButton 渐变

UIButton 背景渐变

示例
let button = UIButton()
button.backgroundGradient(["#B94FF6".hexColor, "#EE6FF3".hexColor], false, .normal)
代码
extension UIButton {
    /// 渐变背景
    @discardableResult
    func backgroundGradient(_ colours: [UIColor],
                                         _ isVertical: Bool = false,
                                         _ state: UIControl.State) -> T {
        let gradientLayer = CAGradientLayer()
        //几个颜色
        gradientLayer.colors = colours.map { $0.cgColor }
        //颜色的分界点
        gradientLayer.locations = [0.2,1.0]
        //开始
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        //结束,主要是控制渐变方向
        gradientLayer.endPoint  = isVertical == true ? CGPoint(x: 0.0, y: 1.0) : CGPoint(x: 1.0, y: 0)
        //多大区域
        gradientLayer.frame = self.bounds.isEmpty ? CGRect(x: 0, y: 0, width: 320, height: 30) : self.bounds
        
        UIGraphicsBeginImageContext(gradientLayer.frame.size)
        
        if let context = UIGraphicsGetCurrentContext() {
            
            gradientLayer.render(in: context)
            
            let outputImage = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            setBackgroundImage(outputImage, for: state)
        }
        return self as! T
    }
}

你可能感兴趣的:(Swift5 UIButton 渐变)