Created
August 18, 2020 13:00
-
-
Save alfian0/96e2ea7523e8ff6c478b02bd0c0d4736 to your computer and use it in GitHub Desktop.
This file contains 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 { | |
public func snapshotImage(bgColor: UIColor? = nil, rect: CGRect? = nil, state: Bool = false) -> UIImage? { | |
var definedRect = CGRect.zero | |
if let rect = rect { | |
definedRect = rect | |
} else { | |
definedRect = self.bounds | |
} | |
UIGraphicsBeginImageContextWithOptions(definedRect.size, false, UIScreen.main.scale) | |
guard let graphicContext = UIGraphicsGetCurrentContext() else { | |
return nil | |
} | |
if bgColor != nil { | |
bgColor!.set() | |
} | |
graphicContext.fill(definedRect) | |
drawHierarchy(in: definedRect, afterScreenUpdates: state) | |
self.layer.isOpaque = false | |
self.layer.render(in: graphicContext) | |
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return snapshotImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment