0

I am trying to render a black rectangle to an image and save it to the photo library. But every time I render it on my iPad, the picture has a white strip on the top, that doesn’t happen if I do this on the iPhone. I am using Swift Playgrounds 4, so maybe that’s the reason. It’s a bit strange, since both Views the small and the bigger one are both „iPads“. Thank you for your help! That’s my code so far:


import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Snapshot") { 
                // Save Screenshot
                let image = snapshotView.snapshot()
                
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }
        }
    }
    var snapshotView: some View {
        VStack {
            Rectangle()
                .frame(width: 200, height: 200)
        }
    }
}

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

Image of the Rectangle

  • This should be helpful https://stackoverflow.com/a/59333377/12299030 - tested on iPad as well - works fine. Xcode 13.4 / iPadOS 15.5 – Asperi Jun 09 '22 at 14:17
  • But is there a way to save the image as an UIImage to photo libary? –  Jun 09 '22 at 17:29
  • call-back, side-effect, modifier, ... anything – Asperi Jun 09 '22 at 17:34
  • Could you please explain it in more detail ? –  Jun 09 '22 at 19:33
  • I have tried it now this way: https://stackoverflow.com/a/59333377/12299030. But the white strip is now on the bottom. It only happens when I tap on the run button, but everything works fine in the preview! –  Jun 10 '22 at 09:52

0 Answers0