通过 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
}
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()
}
}