0

I'm currently attempting to convert a View into an Image following How to convert a UIView to an image.

I essentially want to take a drawn Shape either by the user or pre-made and convert it to a UIView then an Image. These Shape are stacked on top of one another in a ZStack. Something like

ZStack {

  if ... { View1( Shape1() ) }
  else if ... { View2( Shape2().backgroundRectGetter(rect: rect2) }
}
.background(RectGetter(rect: rect1))

I currently convert the Shape to a UIView by using UIHostingController.

UIHostingController(rootView: DrawMyShape()).view but when I convert this to an Image with the extension method linked I get a blank image which I assume means I'm not capturing the right view. When I use it with the rootViewController provided in UIApplication it gives the image of the entire content view.

Any insight onto why this could be happening to help debug? Thank you.

edit: adding link for RectGetter being used with background. How to convert a View (not UIView) to an image?

edit2: adding code

let image1 = UIApplication.shared.windows[0].rootViewController?.view.asImage(rect: self.rect1)

UIImageWriteToSavedPhotosAlbum(image1, nil, nil, nil) // this writes the content view photo

// this writes a blank image
let image 2 = UIHostingController(rootView: Shape2()).view.asImage(rect: self.rect2)

UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)


// RectGetter in other post
struct RectGetter: View {
    @Binding var rect: CGRect
        
    var body: some View {
        GeometryReader { proxy in
            self.createView(proxy: proxy)
        }
    }

    func createView(proxy: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = proxy.frame(in: .global)
        }
        return Rectangle().fill(Color.clear)
    }
}
Paul
  • 1,101
  • 1
  • 11
  • 20
  • 1
    You had me thinking this was `UIKit` with your title - there isn't any such class called `UIView` in `SwiftUI`. Now, you *could* expose a `UIImage` (plus it's `UIImageView`) into SwiftUI and probably send to it an `Image`, but that's not what you're asking, right? Please, give us some details, some code! –  Sep 30 '21 at 23:09
  • @dfd apologies! I'm still very new to iOS. I added code, please let me know if that still is not clear – Paul Sep 30 '21 at 23:17
  • 1
    This can be helpful https://stackoverflow.com/a/59333377/12299030 – Asperi Oct 01 '21 at 04:55

0 Answers0