Skip to content

Instantly share code, notes, and snippets.

@mikehouse
Created February 21, 2019 17:56
Show Gist options
  • Save mikehouse/4b5abbc3b0f10110b92920060853b6ec to your computer and use it in GitHub Desktop.
Save mikehouse/4b5abbc3b0f10110b92920060853b6ec to your computer and use it in GitHub Desktop.
extension UIImage {
func gradientImage(_ colors: [UIColor]) -> UIImage? {
guard let source = withRenderingMode(.alwaysTemplate).cgImage else {
return nil
}
// Create gradient
let cgColors = colors.map({ $0.cgColor })
let colors = cgColors as CFArray
let space = CGColorSpaceCreateDeviceRGB()
guard let gradient = CGGradient(colorsSpace: space,
colors: colors, locations: nil) else {
return nil
}
let renderer = UIGraphicsImageRenderer(
bounds: CGRect(origin: .zero, size: size))
return renderer.image { (context) in
let context = context.cgContext
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1, y: -1)
context.setBlendMode(.normal)
let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
// Apply gradient
context.clip(to: rect, mask: source)
context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0),
end: CGPoint(x: 0, y: size.height), options: .drawsAfterEndLocation)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment