Applying Gradient to UIImage Smoothly

前端 未结 2 1552
孤街浪徒
孤街浪徒 2021-02-09 13:00

I am trying to apply gradient to UIImage using CoreGraphic; however, the result I got is not very nice. I want to create a black to transparent gradient at the bottom of the ima

2条回答
  •  悲&欢浪女
    2021-02-09 13:25

    SWIFT 3

    func imageWithGradient(img:UIImage!) -> UIImage {
    
        UIGraphicsBeginImageContext(img.size)
        let context = UIGraphicsGetCurrentContext()
    
        img.draw(at: CGPoint(x: 0, y: 0))
    
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 1.0]
    
        let bottom = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor
        let top = UIColor(red: 0, green: 0, blue: 0, alpha: 0).cgColor
    
        let colors = [top, bottom] as CFArray
    
        let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations)
    
        let startPoint = CGPoint(x: img.size.width/2, y: 0)
        let endPoint = CGPoint(x: img.size.width/2, y: img.size.height)
    
        context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: UInt32(0)))
    
        let image = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return image!
    }
    

提交回复
热议问题