Skip to content

Instantly share code, notes, and snippets.

@alfian0
Created August 18, 2020 13:00
Show Gist options
  • Save alfian0/96e2ea7523e8ff6c478b02bd0c0d4736 to your computer and use it in GitHub Desktop.
Save alfian0/96e2ea7523e8ff6c478b02bd0c0d4736 to your computer and use it in GitHub Desktop.
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