Home > Back-end >  When converting SwiftUI view to image, it doesn't work as expected
When converting SwiftUI view to image, it doesn't work as expected

Time:09-09

My goal is to convert SwiftUI view to image. I am currently building it for iOS 15 here is the code that converts the view to image

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        
        let targetSize = controller.view.intrinsicContentSize
        
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

Expected result: enter image description here

  • Related