异步呈现的Swift UI Center Image

7gs2gvoe  于 2024-01-05  发布在  Swift
关注(0)|答案(1)|浏览(123)

我想将一个图像放置在屏幕的中心。我使用的是来自KingFisher库的KFImage来渲染和显示来自Web的图像。这些图像不是立即渲染的,所以onAppear方法并不总是足以计算图像大小。在VStack中使用2个间隔符也不起作用。将对齐设置为中心也不起作用。我下面的方法效果很好对于UIImages,但由于onAppear执行时图像可能不会呈现,有时会失败。如何使图像居中?

  1. KFImage(URL(string: image))
  2. .resizable()
  3. .aspectRatio(contentMode: .fit)
  4. .offset(x: (screenWidth() - imageWidth) / 2.0, y: (screenHeight() - imageHeight) / 2.0)
  5. .background (
  6. GeometryReader { proxy in
  7. Color.clear
  8. .onAppear {
  9. imageHeight = proxy.size.height
  10. imageWidth = proxy.size.width
  11. }
  12. .onChange(of: currentStory) { _ in
  13. imageHeight = proxy.size.height
  14. imageWidth = proxy.size.width
  15. }
  16. }
  17. )

字符串

l2osamch

l2osamch1#

我认为最简单的方法是把它放进ZStack,它总是居中的,不管图像的大小是多少。

  1. var body: some View {
  2. ZStack {
  3. KFImage(url)
  4. .resizable()
  5. .aspectRatio(contentMode: .fit)
  6. }
  7. }

字符串
下面所附的图像是VStack,包括上面的文本和ZStack。


的数据

相关问题