异步呈现的Swift UI Center Image

7gs2gvoe  于 5个月前  发布在  Swift
关注(0)|答案(1)|浏览(52)

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

KFImage(URL(string: image))
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .offset(x: (screenWidth() - imageWidth) / 2.0, y: (screenHeight() - imageHeight) / 2.0)
                            .background (
                                GeometryReader { proxy in
                                    Color.clear
                                        .onAppear {
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                        .onChange(of: currentStory) { _ in
                                            imageHeight = proxy.size.height
                                            imageWidth = proxy.size.width
                                        }
                                }
                            )

字符串

l2osamch

l2osamch1#

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

var body: some View {
    ZStack {
        KFImage(url)
            .resizable()
            .aspectRatio(contentMode: .fit)
    }
}

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


的数据

相关问题