Search code examples
iosswiftuiimageuikitgradient

How to show a gradient diagonally in a view


I am generating a gradient from 2 UIColors and then generating a UIImage out of it using these functions.

//Function to generate the UIImage from 2 colors.
func createGradient(color1: UIColor, color2: UIColor) -> UIImage {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.bounds
    gradientLayer.colors = [color1.cgColor, color2.cgColor]
    let image = image(from: gradientLayer)
    return image
}

//Function to generate an Image from a CALayer.
func image(from layer: CALayer) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, true, 0)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return outputImage ?? UIImage()
}

My result is this

enter image description here

But I would like to show this diagonally from the top left corner to the bottom right corner .... So the Red should start from the top left corner and fade into the Yellow as it goes down diagonally towards the bottom right corner.

I am not sure if should be generating the Gradient diagonally or if i should rotate the image after it is generated to show it diagonally.

Thanks


Solution

  • Simply add the startPoint and endPoint to the gradient layer:

    [...]
    gradientLayer.startPoint = .init(x: 0, y: 0) // top left
    gradientLayer.endPoint = .init(x: 1, y: 1) // bottom right
    [...]