swiftui - 来自 View 的 UIImage 与 onAppear 逻辑
问题描述
当我在 View 中有任何逻辑时,我在渲染 SwiftUI 时遇到了View
麻烦。UIImage
onAppear
例如,这里我们有一个SnapshotViewTest
,它有一个Button
并且应该创建一个快照AGreatView
并显示UIImage
结果。AGreatView
只有逻辑开启onAppear
- 将 of 设置为width
我Color.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)
}
}
}
谢谢你的任何想法!
解决方案
你可以试试这个,对我有用:
Button("Make a snapshot of a great view", action: {
let view = AGreatView()
DispatchQueue.main.async {
uiImage = view.snapshot()
}
})
不需要DispatchQueue
in AGreatView
onAppear
。
如果这仍然对您不起作用,请尝试引入一个小的延迟,例如:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
推荐阅读
- python - 列表对象的python变量名,最佳实践
- r - R:按数据集分组,条件是组中特定列中的所有值都符合某些要求
- r - 如何在 R 中按中位数或众数填充 NA
- nginx - 为什么浏览器在响应 413 的情况下显示 CORS 错误?
- google-bigquery - 用于扩展 json 以记录的 BigQuery UDF
- javascript - 从对象的数据数组中填充视图 Angular
- r - R中删除的小数位
- google-apps-script - Google App Script 读取特定文件夹中的文件
- c - fscanf 上的分段错误
- java - 为什么 addNode() 方法返回编译错误“方法...类型...不适用于参数...”,我该如何解决?