颜色渐变

 public class func gradientColor(_ startPoint: CGPoint, endPoint: CGPoint, frame: CGRect, colors: [UIColor]) -> UIColor? {
        // init a CAGradientLayer and set its frame
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = frame
        
        // turn the array of UIColor's into an array of CGColor's
        let cgColors = colors.map({$0.cgColor})
        
        // set the colors of the gradient
        gradientLayer.colors = cgColors
        
        // set the start and end points of the gradient
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        // start an image context
        UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, UIScreen.main.scale)
        
        // draw the gradient layer in the context
        gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
        
        // get the image of the gradient from the current image context
        let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // end the context
        UIGraphicsEndImageContext()
        
        // return a new UIColor using the gradient image we made
        return UIColor(patternImage: gradientImage!)
    }

 public class func radialGradientColor(_ frame: CGRect, colors: [UIColor]) -> UIColor? {
        // start the image context
        UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale)
        
        // get an array of CGColor's from the UIColor's
        let cgColors = colors.map({$0.cgColor})
        
        // init a color space
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        
        // get a CFArrayRef from our array of CGColor's
        let arrayRef = cgColors as CFArray
        
        // init the gradient
        let gradient = CGGradient(colorsSpace: colorSpace, colors: arrayRef, locations: nil)
        
        // make the center point in the center
        let centrePoint = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
        
        // calculate the radius from the frame
        let radius = max(frame.size.width, frame.size.height)/2
        
        // draw the radial gradient
        UIGraphicsGetCurrentContext()?.drawRadialGradient(gradient!,
                                     startCenter: centrePoint,
                                     startRadius: 0,
                                     endCenter: centrePoint,
                                     endRadius: radius,
                                     options: .drawsAfterEndLocation)
        
        // get a UIImage from the current context
        let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // return a new UIColor from the radial gradient we just made
        return UIColor(patternImage: gradientImage!)
    }

你可能感兴趣的:(颜色渐变)