给 view设置渐变色背景,生成渐变 UIImage

通过 CAGradientLayer 实现

 		let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [UIColor(R: 241, G: 173, B: 17, alpha: 1).cgColor, UIColor(R: 210, G: 166, B: 8, alpha: 1).cgColor, UIColor(R: 237, G: 178, B: 60, alpha: 0).cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 0, y: 1)
        gradientLayer.locations = [0, 0.5, 0.8]
        gradientLayer.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenWidth * 0.685 + (isNotchScreen ? 24: 0))
        self.contentView.layer.addSublayer(gradientLayer)

通过生成 UIImage 设置背景

extension UIImage {

    enum XFSGradientType {
        case topToBottom
        case leftToRight
        case topLeftToBottomRight
        case topRightToBottomLeft
    }

    /// 生成渐变色图片
    /// - Parameters:
    ///   - colors: 开始颜色,终止颜色,以及过度色
    ///   - type: 渐变方向
    ///   - locations: 每个颜色在渐变色中的位置,值介于0.0-1.0之间
    ///   - size: 图片大小
    convenience init(colors: [UIColor], gradientType type: XFSGradientType, locations: [CGFloat], size: CGSize) {
        assert(colors.count == locations.count, "渐变数组与颜色位置数组 count 不一致")
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        context?.saveGState()
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let cgColors = colors.compactMap { (color) -> CGColor in
            return color.cgColor
        }

        guard let gradient = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: locations) else {
            self.init()
            return
        }
        switch type {
        case .leftToRight:
            context?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: size.width, y: 0), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
        case .topToBottom:
            context?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
        case .topLeftToBottomRight:
            context?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: size.width, y: size.height), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
        case .topRightToBottomLeft:
            context?.drawLinearGradient(gradient, start: CGPoint(x: size.width, y: 0), end: CGPoint(x: 0, y: size.height), options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
        }
        if let newImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage {
            self.init(cgImage: newImage)
        }else {
            self.init()
        }
        context?.restoreGState()
        UIGraphicsEndImageContext()
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值