I have an app where I convert variable sized UIView to UIImage.
Problem is that when UIView becomes too large, UIGraphicsGetImageFromCurrentImageContext crashes. Logs show root cause is OS running out of memory.
This is my code:
public extension UIView {
func snapshotImage(rectangle: CGRect) -> UIImage? {
var image: UIImage?
autoreleasepool { () -> () in
UIGraphicsBeginImageContextWithOptions(rectangle.size, isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
context.translateBy(x: -rectangle.origin.x, y: -rectangle.origin.y)
layer.render(in: context)
image = UIGraphicsGetImageFromCurrentImageContext()
}
}
return image
}
}
I tried using UIGraphicsImageRenderer, something like:
extension UIView {
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
When using UIGraphicsImageRenderer app does not crash, but it fails to create resulting image, so the result is unusable.
Any idea on how to solve converting large UIViews to UIImages properly?