Skip to content

Instantly share code, notes, and snippets.

@alongotv
Created July 3, 2019 14:22
Show Gist options
  • Save alongotv/788b6236324de57c7637d4e610343cee to your computer and use it in GitHub Desktop.
Save alongotv/788b6236324de57c7637d4e610343cee to your computer and use it in GitHub Desktop.
Function to generate an image consisting of a gradient between 2 colors
func imageWithGradient(startColor: UIColor, endColor: UIColor, size: CGSize, horizontally: Bool = true) -> UIImage? {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
if horizontally {
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
} else {
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
}
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment