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