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

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

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

宽度相同

enter image description here

使用

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)

哪个更糟糕!

enter image description here

如有任何帮助,我们将不胜感激!使用

.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)

enter image description here

swift swiftui
4个回答
4
投票

仅使用 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)

1
投票

尝试使用

scaledToFill
clipped
修饰符

    VStack{
        AnimatedImage(url: URL(string: self.mediaLink))
            .resizable()
            .scaledToFill()
            .frame(width: UIScreen.main.bounds.width - 40)
            .clipped()
    }
    .frame(width: UIScreen.main.bounds.width - 40)

0
投票

我认为这个改变会对你有所帮助:

VStack {
    AnimatedImage(url: URL(string: self.mediaLink))
       .resizable()
       .scaledToFit()
}
.frame(width: UIScreen.main.bounds.width - 40)

0
投票

所有这些答案都使用

UIScreen.main.bounds.width
,这是一个坏主意。

如果视图位于表单中,或者在 iPad 上的侧边栏布局中使用怎么办?如果设置后容器的大小发生变化怎么办?您不应该使用这样的数字大小。

相反,请使用 containerRelativeFrame 修饰符:

      Image("some_image")
        .resizable()
        .scaledToFit()
        .containerRelativeFrame(.horizontal)  { size, axis in
          size
        }

这会将图像的宽度设置为其容器的精确宽度,甚至会随着容器大小的变化而更新。

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