首页 > 解决方案 > 来自 View 的 UIImage 与 onAppear 逻辑

问题描述

当我在 View 中有任何逻辑时,我在渲染 SwiftUI 时遇到了View麻烦。UIImageonAppear

例如,这里我们有一个SnapshotViewTest,它有一个Button并且应该创建一个快照AGreatView并显示UIImage结果。AGreatView只有逻辑开启onAppear- 将 of 设置为widthColor.green想在屏幕上显示的 50。

它应该是这样的: 这就是它的样子

这是它的样子: 在此处输入图像描述

这是SnapshotViewTest

struct SnapshotViewTest: View {
    @State var uiImage = UIImage()
    var body: some View {
        VStack {
            Button("Make a snapshot of a great view", action: {
                let view = AGreatView()
                
                uiImage = view.animation(nil).snapshot()
            })
            Image(uiImage: uiImage)
        }
    }
    
    struct AGreatView: View {
        @State var width = 0.0
        var body: some View {
            VStack {
                Text("Some text")
                Color.green.frame(width: width, height: 10) //works when I set "width" to any Double
            }.padding()
                .background(Color.red.opacity(0.1))
            .onAppear {
                DispatchQueue.main.async { //does not make any difference without
                    width = 50
                }
            }
        }
    }
}

这是我的观点snapshot func

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)
                
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        
        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
        
    }
}

谢谢你的任何想法!

标签: swiftuiuikituiimage

解决方案


你可以试试这个,对我有用:

Button("Make a snapshot of a great view", action: {
    let view = AGreatView()
    DispatchQueue.main.async {
        uiImage = view.snapshot()
    }
})

不需要DispatchQueuein AGreatView onAppear

如果这仍然对您不起作用,请尝试引入一个小的延迟,例如:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)

推荐阅读