UIImage from snapshot view?

On iOS, I'm trying to convert the contents of a view produced by snapshotView(afterScreenUpdates:) into a UIImage. At the point where I'm trying to do this, I no longer have the underlying objects that were rendered into the snapshot - I only have the snapshot view.


Although this snapshot view displays correctly on the device screen at all times, I seem to be unable to convert it to an image to save to disk.


For example, say I do something like:


let ssView = someView.snapshotView(afterScreenUpdates:true)


And then later, I want to convert ssView to a UIImage. I have tried all the usual patterns that work with other (non-snapshot) views such as:


UIGraphicsBeginImageContext(ssView.frame.size)

ssView.drawHierarchy(in: ssView.bounds, afterScreenUpdates: true)

let image = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

or

let renderer = UIGraphicsImageRenderer(size: ssView.frame.size)

let image = renderer.image {

context in

return ssView.layer.render(in: context.cgContext)

}


And many other variations... I've also tried to render the hierarchy from superviews of the snapshot view but no matter what I try, it doesn't work. Attempting to capture the snapshot view directly produces a blank image and if the parent view is captured, the portion of the screen where the snapshot view resides is blank.


Does anyone have any idea how to make this work?


Thanks,

David




Replies

It's not possible to render UIView based snapshot into the image for security reasons. UIView based snapshots can capture out of process content (e.g. remote views from extensions), thus it's not possible to get image bits out of it. If you go into your use case in more details (why you need image in a first place), I might help with alternatives. However, we don't recommend to capturing views as images, because such images can/will go obsolete when system settings change (e.g. light -> dark mode, font size, etc.).

Hello,

I'm facing a similar issue...I'm working on an artistic "masterpiece creation" app where the user can put several icons on a canvas and I just want to take a snapshot of what the user composed to create a gallery with the images. The problem is that the snapshot creation ignores every modifier of the icons...I let the user change the position, scale and rotation of every icon on the canvas but the screenshot ignores all of them and creates an image with all the icons overlapped in the center.

I've tried, like David, every possible way of snapshotting a view.

Any solution?

Thanks, Vincenzo