Skip to content

Instantly share code, notes, and snippets.

@cristianca
Last active April 14, 2023 18:25
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cristianca/431cdeb39bc53a979a4e to your computer and use it in GitHub Desktop.
Save cristianca/431cdeb39bc53a979a4e to your computer and use it in GitHub Desktop.
Create a gradient UIColor from an array of colors.
func colorWithGradient(frame: CGRect, colors: [UIColor]) -> UIColor {
// create the background layer that will hold the gradient
let backgroundGradientLayer = CAGradientLayer()
backgroundGradientLayer.frame = frame
// we create an array of CG colors from out UIColor array
let cgColors = colors.map({$0.CGColor})
backgroundGradientLayer.colors = cgColors
UIGraphicsBeginImageContext(backgroundGradientLayer.bounds.size)
backgroundGradientLayer.renderInContext(UIGraphicsGetCurrentContext())
let backgroundColorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIColor(patternImage: backgroundColorImage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment