Dear Richard
Thanks for your further advice.
I made followings, did I code what you said?
or more other effective and simplified way available?
struct CaptureContainer<Content: View>: UIViewRepresentable {
@Binding var hostView: UIView?
let content: Content
init(
hostView: Binding<UIView?>,
@ViewBuilder content: () -> Content
) {
self._hostView = hostView
self.content = content()
}
func makeUIView(context: Context) -> UIView {
let container = UIView()
container.backgroundColor = .white
let hosting = UIHostingController(rootView: content)
hosting.view.backgroundColor = .white
hosting.view.translatesAutoresizingMaskIntoConstraints = false
hosting.view.isUserInteractionEnabled = true
container.addSubview(hosting.view)
NSLayoutConstraint.activate([
hosting.view.topAnchor.constraint(equalTo: container.topAnchor),
hosting.view.bottomAnchor.constraint(equalTo: container.bottomAnchor),
hosting.view.leadingAnchor.constraint(equalTo: container.leadingAnchor),
hosting.view.trailingAnchor.constraint(equalTo: container.trailingAnchor)
])
DispatchQueue.main.async {
self.hostView = hosting.view
}
return container
}
func updateUIView(_ uiView: UIView, context: Context) {}
}
and My Home View is
struct HomeView: View {
@State private var captureView: UIView?
var body: some View {
CaptureContainer(hostView: $captureView) {
VStack {
HStack {
ImageView()
InfoView(
hostView: $captureView
)
}
ActionView()
}
}
.ignoresSafeArea()
}
}
and
struct InfoView:View{
@Binding var hostView: UIView?
@State var uiImage: UIImage? = nil
var body: some View {
Button(action: {
screenShot(captureView: hostView)
}){
Text("Save")
}
}
}
func screenShot(captureView:UIView?){
self.uiImage = captureScreenshot(captureView: captureView)
}
func captureScreenshot(captureView:UIView?) -> UIImage? {
guard let view = captureView else { return nil }
return view.captureHierarchyImage()
}
extension UIView {
func captureHierarchyImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { _ in
drawHierarchy(in: bounds, afterScreenUpdates: true)
}
}
}