swift - 如何在 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)
解决方案
如下所示仅使用 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)
推荐阅读
- java - 列“_id”不存在。可用列:[_Id,产品]
- python - Pandas Groupby (shift) 函数为第一个条目返回 null
- templates - 如何使用 helm 更新数组中的属性?
- angular - 在 Angular 中编码 URL 参数
- oracle - 尝试将表 1 中的数据插入表 2 时值不足
- c# - 如何将我的 IIS 网站移动到默认网站下?
- linux - 随机选择文件并将其添加到另一个文件夹中的数据中
- python - 聚合置信区间 statsmodel OLS
- android - 更新到 4.1 时 Android Studio 启动失败
- reactjs - 用 razzle 获取错误输出