如何在 SwiftUI 中使图像的宽度达到其容器的 100%?

mar*_*usp 7 swift swiftui

我让用户从他们的移动设备上传图像,这些图像可以是纵向或横向的。我将这些图像平铺起来,类似于 Instagram 帖子。我遇到的最大问题是肖像图像没有以 100% 的容器宽度渲染。实在是太奇怪了。

这是我拍摄的“肖像”照片的示例,并使用以下代码进行可视化:

VStack{
    AnimatedImage(url: URL(string: self.mediaLink))
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.padding(.horizontal, 20)
.frame(width: UIScreen.main.bounds.width - 40)
Run Code Online (Sandbox Code Playgroud)

即使我指定了宽度,它仍然呈现不正确。它应该是UIScreen.main.bounds.width - 40,与其父级宽度相同VStack

在此输入图像描述

使用时GeometryReader,我的代码如下所示:

GeometryReader{geo in
    VStack{
        AnimatedImage(url: URL(string: self.mediaLink))
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: geo.size.width)
    }
}
.frame(width: UIScreen.main.bounds.width)
Run Code Online (Sandbox Code Playgroud)

哪个更糟糕!

在此输入图像描述

任何帮助表示赞赏!使用.fill纵横比会使图像太大,并遮挡卡中的所有内容。下面的代码没有使用GeometryReader

VStack{
    AnimatedImage(url: URL(string: self.mediaLink))
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.frame(width: UIScreen.main.bounds.width - 40)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Asp*_*eri 3

仅使用 Image("some_image") 测试了您的代码,如下所示,它可以工作(Xcode 12 / iOS 14),因此问题要么在其他代码中,AnimatedImage要么在其他代码中。

VStack{
    Image("some_image")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.padding(.horizontal, 20)
.frame(width: UIScreen.main.bounds.width - 40)
Run Code Online (Sandbox Code Playgroud)