Created
February 21, 2019 17:56
-
-
Save mikehouse/4b5abbc3b0f10110b92920060853b6ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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