创建 CAGradientLayer
// View to hold the CAGradientLayer.
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 320))
// Initialize gradient layer.
let gradientLayer: CAGradientLayer = CAGradientLayer()
// Set frame of gradient layer.
gradientLayer.frame = view.bounds
// Color at the top of the gradient.
let topColor: CGColor = UIColor.red.cgColor
// Color at the bottom of the gradient.
let bottomColor: CGColor = UIColor.yellow.cgColor
// Set colors.
gradientLayer.colors = [topColor, bottomColor]
// Set locations of the colors.
gradientLayer.locations = [0.0, 1.0]
// Insert gradient layer into view's layer heirarchy.
view.layer.insertSublayer(gradientLayer, at: 0)
结果: