Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Created November 9, 2016 13:43
Show Gist options
  • Save michaelevensen/fd7f4814fe32e7f751556c4fb2f56956 to your computer and use it in GitHub Desktop.
Save michaelevensen/fd7f4814fe32e7f751556c4fb2f56956 to your computer and use it in GitHub Desktop.
extension UIImage {
class func imageWithLayer(layer: CALayer) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, layer.isOpaque, 0.0)
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
return img
}
}
// Get UIImage from CAGradientLayer
let gradientOverlayLayer = CAGradientLayer()
UIImage.imageWithLayer(layer: gradientOverlayLayer)?.draw(at: CGPoint.zero, blendMode: .multiply, alpha: 1.0)
@michaelevensen
Copy link
Author

As a side not define extensions with class func to allow them to be initialized in the form of UIImage.imageWithLayer() instead of UIImage().imageWithLayer()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment