首页 > 解决方案 > 如何在 SwiftUI 中使图像的容器宽度达到 100%?

问题描述

我有用户从他们的移动设备上传图像,这些图像可以是纵向或横向的。我将这些图像平铺,类似于 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)

即使我指定了宽度,它仍然呈现不正确。应该是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)

哪个更糟!

在此处输入图像描述

任何帮助表示赞赏!使用.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)

在此处输入图像描述

标签: swiftswiftui

解决方案


如下所示仅使用 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)

推荐阅读