如何在SwiftUI中使图像的宽度达到其容器的100%?
我让用户从他们的移动设备上传图像,这些图像可以是纵向的,也可以是横向的。我将这些图片平铺成类似Instagram的帖子。我遇到的最大问题是,肖像图像不能以100%的容器宽度进行渲染。这真的很奇怪 下面是我拍摄的一张“肖像”照片的示例,使用以下代码进行可视化:如何在SwiftUI中使图像的宽度达到其容器的100%?,swift,swiftui,Swift,Swiftui,我让用户从他们的移动设备上传图像,这些图像可以是纵向的,也可以是横向的。我将这些图片平铺成类似Instagram的帖子。我遇到的最大问题是,肖像图像不能以100%的容器宽度进行渲染。这真的很奇怪 下面是我拍摄的一张“肖像”照片的示例,使用以下代码进行可视化: VStack{ AnimatedImage(url: URL(string: self.mediaLink)) .resizable() .aspectRatio(contentMode: .fit)
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)
我认为这一变化将有助于您:
VStack {
AnimatedImage(url: URL(string: self.mediaLink))
.resizable()
.scaledToFit()
}
.frame(width: UIScreen.main.bounds.width - 40)
尝试使用
scaledToFill
和clipped
修饰符
VStack{
animateImage(url:url(字符串:self.mediaLink))
.可调整大小()
.scaledToFill()
.frame(宽度:UIScreen.main.bounds.width-40)
.clipped()
}
.frame(宽度:UIScreen.main.bounds.width-40)
只使用下面的图像(“一些图像”)测试代码,它可以正常工作(Xcode 12/iOS 14),因此问题要么出现在动画图像中,要么出现在其他一些代码中
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)
仅使用图像(“some_Image”)
对代码进行了测试,它可以正常工作,因此问题可能出现在AnimatedImage
或其他一些代码中。如果您在画布中查看完整视图的预览,您是否看到VStack的宽度与您编写的第一个示例的图像相同?这可能与高度有关,因为实验中您是否尝试将高度固定在接近图像预期高度的位置?@Asperi是正确的。问题在于AnimatedImage。我正在为我的项目使用此依赖项。我所要做的就是将AnimatedImage
更改为WebImage
。如果你发帖,我会标记为已回复。:)