Created
November 7, 2016 14:16
-
-
Save peatiscoding/83852abe8150e66da1b3b4855e8f7b84 to your computer and use it in GitHub Desktop.
An easy way to create a UIImage snapshot from given view.
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 UIView { | |
| func snapshot() -> UIImage { | |
| UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.mainScreen().scale) | |
| self.layer.renderInContext(UIGraphicsGetCurrentContext()!) | |
| let img = UIGraphicsGetImageFromCurrentImageContext() | |
| UIGraphicsEndImageContext() | |
| return img | |
| } | |
| } |
Author
π
Swift 5 version:
extension UIView {
func snapshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
ππ»
More safe approach (without force unwrap).
extension UIView {
func snapshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, true, UIScreen.main.scale)
guard let currentContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
layer.render(in: currentContext)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simply call: