Saving SwiftUi View as an image to photo album

Viewed 78

I'm using extension to View I found on hackingwithswift.com:

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)
        }
    }
}

I'm using in the following way:

I have object of type Canvas, which contains some drawing and I also added a border to make it more visible. Then I'm saving it to Photo Album, but finall photo is is out of position in relation to the original. I'm attaching screenshot of my view and finall photo.

let image = canvas.snapshot()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

view

result

1 Answers

Add .edgesIgnoringSafeArea(.all) to the rootView: self parameter of the UIHostingController init call.

let controller = UIHostingController(rootView: self.edgesIgnoringSafeArea(.all))

That will make the screenshot not be clipped.

Related