如何在SwiftUI中使图像的宽度完全等于其容器的宽度?

6
我可以帮助您进行翻译。以下是需要翻译的内容:

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


测试了你的代码,只使用 Image("some_image") 就可以正常工作,因此问题可能出在 AnimatedImage 或其他代码中。 - Asperi
如果您在画布中查看完整视图的预览,是否看到VStack的宽度与您编写的第一个示例中的图像相同?这可能与高度有关,作为实验,您是否尝试将高度固定为接近预期高度的值? - SwissMark
@Asperi 是正确的。问题出在 AnimatedImage 上。我正在使用这个依赖项来完成我的项目。https://github.com/SDWebImage/SDWebImageSwiftUI。我所要做的就是将 AnimatedImage 更改为 WebImage。如果您发布,我会标记为已回答。 :) - markusp
3个回答

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)

1
尝试使用 scaledToFillclipped 修饰符。
    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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接