Convert View to Image for Share

Hello everyone,

I need your help to convert my view in order to share it as an image:

On one of my "VStack" views, I would like to convert this view into an Image and share it via the "ShareLink" function

How can I convert a simple view to an Image?

For example:

ZStack {
    Rectangle()
                    .fill(Color.blue.opacity(0.70))
                    .cornerRadius(16)
                
    VStack {
        Text("Share Text")
    }
}




Thank You for your help !

Answered by HamstersTech1 in 784552022

You can convert view to image with this function

func convertViewToImage( ) -> UIImage {

    let view = UIHostingController(rootView: AnyView(self.body))
    let size = view.view.bounds.size
    view.view.frame = CGRect(origin: .zero, size: size)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image = renderer.image { context in
        view.view.layer.render(in: context.cgContext)
    }
    return image
}
Accepted Answer

You can convert view to image with this function

func convertViewToImage( ) -> UIImage {

    let view = UIHostingController(rootView: AnyView(self.body))
    let size = view.view.bounds.size
    view.view.frame = CGRect(origin: .zero, size: size)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image = renderer.image { context in
        view.view.layer.render(in: context.cgContext)
    }
    return image
}

Hello !

thank you for your help ! this helped me a lot ! I didn't know about the "UIGraphicsImageRenderer" function.

thank you !

Convert View to Image for Share
 
 
Q