【发布时间】:2021-10-16 09:13:10
【问题描述】:
当我在 View 的 onAppear 中有任何逻辑时,我无法将 SwiftUI View 渲染为 UIImage。
例如,这里我们有一个SnapshotViewTest,它有一个Button,应该制作AGreatView 的快照并显示UIImage 结果。 AGreatView 仅在 onAppear 上具有逻辑 - 将 Color.green 的 width 设置为我希望在屏幕上显示的 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)
}
}
}
感谢您的任何想法!
【问题讨论】: