Drawing gradient over image in ios

后端 未结 5 642
天涯浪人
天涯浪人 2020-12-08 11:55

How to create gradient colour look like following image programatically.

\"enter

5条回答
  •  感情败类
    2020-12-08 13:00

    I just wrote an UIImage extension for Swift 2.0. Maybe it's of some use. You call it with an array of UIColor (any number) and a frame where the gradient should be drawn.

    extension UIImage {
    
        class func convertGradientToImage(colors: [UIColor], frame: CGRect) -> UIImage {
    
            // start with a CAGradientLayer
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = frame
    
            // add colors as CGCologRef to a new array and calculate the distances
            var colorsRef = [CGColor]()
            var locations = [NSNumber]()
    
            for i in 0 ... colors.count-1 {
                colorsRef.append(colors[i].CGColor as CGColorRef)
                locations.append(Float(i)/Float(colors.count-1))
            }
    
            gradientLayer.colors = colorsRef
            gradientLayer.locations = locations
    
            // now build a UIImage from the gradient
            UIGraphicsBeginImageContext(gradientLayer.bounds.size)
            gradientLayer.renderInContext(UIGraphicsGetCurrentContext()!)
            let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            // return the gradient image
            return gradientImage
        }
    }
    

    Call it like this:

    let colors = [
        UIColor.blueColor(),
        UIColor.greenColor()
        // and many more if you wish
    ]
    let gradientImage = UIImage.convertGradientToImage(colors, frame: navigationBar.bounds)
    

    and apply with:

    .backgroundColor = UIColor(patternImage: gradientImage)
    

    or

    .setBackgroundImage(gradientImage, forBarMetrics: .Default)
    

提交回复
热议问题