How to take a snapshot programmatically on visionOS?

Hi there. I've been trying to take a snapshot programmatically on apple vision pro but haven't succeeded.

This is the code I am using so far:

func takeSnapshot<Content: View>(of view: Content) -> UIImage? {
        var image: UIImage?
        uiQueue.sync {
            let controller = UIHostingController(rootView: view)
            controller.view.bounds = UIScreen.main.bounds
            let renderer = UIGraphicsImageRenderer(size: controller.view.bounds.size)
            image = renderer.image { context in
                controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
            }
        }
        return image
    }

However, UIScreen is unavailable on visionOS.

Any idea of how I can achieve this? Thanks

Oscar

Answered by Vision Pro Engineer in 787738022

UIScreen is unavailable in visionOS, but you can set the bounds of the UIHostingViewController to whatever size you'd like. This size determines the final size of the image. You will want to choose an appropriate size depending on your use case. I was able to create a 200x150 image using your by setting controller.view.bounds with the following line of code:

controller.view.bounds = .init(origin: .zero, size: .init(width: 200, height: 150))

Hope this helps,

Michael

UIScreen is unavailable in visionOS, but you can set the bounds of the UIHostingViewController to whatever size you'd like. This size determines the final size of the image. You will want to choose an appropriate size depending on your use case. I was able to create a 200x150 image using your by setting controller.view.bounds with the following line of code:

controller.view.bounds = .init(origin: .zero, size: .init(width: 200, height: 150))

Hope this helps,

Michael

How to take a snapshot programmatically on visionOS?
 
 
Q