Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying Gradient to UIImage Smoothly

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 image to create a contrast for me to place some text. However, the gradient I was able doesn't blend well with the image; you can clearly see the separation in the center. The result I am looking for is like this application: http://capptivate.co/2014/02/17/yummly-3/ How should I apply the gradient to achieve this? ( I have to apply this to large quantity of images ).

My Result:

enter image description here

Here is my code:

func imageWithGradient(img:UIImage!) -> UIImage{

    UIGraphicsBeginImageContext(img.size)
    var context = UIGraphicsGetCurrentContext()

    img.drawAtPoint(CGPointMake(0, 0))

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let locations:[CGFloat] = [0.50, 1.0]
    //1 = opaque
    //0 = transparent
    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 gradient = CGGradientCreateWithColors(colorSpace,
        [top, bottom], locations)


    let startPoint = CGPointMake(img.size.width/2, 0)
    let endPoint = CGPointMake(img.size.width/2, img.size.height)

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)

    let image = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return image
}
like image 669
harinsa Avatar asked Mar 17 '15 17:03

harinsa


1 Answers

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!
}
like image 176
Miralem Cebic Avatar answered Oct 18 '22 09:10

Miralem Cebic