如何让图像填满屏幕并在 SwiftUI 中居中

问题描述 投票:0回答:1

我想显示一个充满屏幕并使图像居中的 AsyncImage。这是一个示例,但它是顶部领先对齐的。

struct ContentView: View {
    var body: some View {
        AsyncImage(url: URL(string: "https://www.apple.com/v/home/bn/images/promos/ipad-air/promo_ipadair_announce__eqsaj3vip4om_large_2x.jpg")) { image in
            image
                .resizable()
                .aspectRatio(contentMode: .fill)
                .ignoresSafeArea()
        } placeholder: {
            ProgressView()
        }
    }
}
swift swiftui
1个回答
0
投票

图像未从顶部对齐,但也不居中。这是在运行 iOS 17.5 (Xcode 15.4) 的 iPhone 15 模拟器上运行时的样子:

Screenshot

这张特定的图像相当宽,但主要拍摄对象在水平方向上居中得很好,因此当缩放以填充时,应该看到它是水平居中的。

如果您使用

GeometryReader
来测量屏幕尺寸并将其作为
.frame
应用于图像,效果会更好:

GeometryReader { proxy in
    AsyncImage(url: URL(string: "https://www.apple.com/v/home/bn/images/promos/ipad-air/promo_ipadair_announce__eqsaj3vip4om_large_2x.jpg")) { image in
        image
            .resizable()
            .scaledToFill()
            .frame(width: proxy.size.width, height: proxy.size.height)
    } placeholder: {
        ProgressView()
    }
}
.ignoresSafeArea()

Screenshot

© www.soinside.com 2019 - 2024. All rights reserved.