【发布时间】:2019-09-12 16:57:45
【问题描述】:
我正在与VStack 合作以显示图像(它们将是几个不同大小的 json)
我需要显示它以占据屏幕宽度(vstack 的宽度并保持纵横比)并适当调整大小,根据屏幕宽度尊重高度。 我尝试了不同的方式,但我设法正确显示图像。
我的观点是:
struct ContentView: View {
var body: some View {
VStack {
GeometryReader { geometry in
VStack {
Text("Width: \(geometry.size.width)")
Text("Height: \(geometry.size.height)")
}
.foregroundColor(.white)
}
.padding()
.frame(alignment: .topLeading)
.foregroundColor(Color.white) .background(RoundedRectangle(cornerRadius: 10) .foregroundColor(.blue))
.padding()
GeometryReader { geometry in
VStack {
Image("sample")
.resizable()
//.frame(width: geometry.size.width)
.aspectRatio(contentMode: .fit)
}
.foregroundColor(.white)
}
.frame(alignment: .topLeading)
.foregroundColor(Color.white) .background(RoundedRectangle(cornerRadius: 10) .foregroundColor(.blue))
.padding()
}
.font(.title)
}
}
当我通过分配geometry 的宽度来使用.frame (width: geometry.size.width) 时,宽度会显示在整个屏幕上,但高度不会保持纵横比。 (看起来很崩溃)
如何获取图像的尺寸并找到其比例以将其与.aspectRatio (myratio, contentMode: .fit) 一起使用
还有另一种方法可以正确显示图像,任何建议
【问题讨论】:
-
不确定这是否可行,但您是否尝试将宽度设置为
.infinite? -
是的:
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: Alignment.topLeading)它显示为第一个选项。与:.frame(minWidth: 0, maxWidth: geometry.size.width, minHeight: 0, maxHeight: .infinity, alignment: Alignment.topLeading)这对我也不起作用 -
最后一个想法 - 今天晚些时候我会看看是否还有其他问题。您是否尝试过更改修饰符的顺序?特别是#2。 (我们都知道
resizable需要在aspectRatio之前。你试过让frame成为第三个修饰符吗? -
对不起,但这让我比我想象的要早检查。 :-) 我使用运行 iPadOS 13.1 的 iPad Mini 选择了自己的图像。在纵向中,它按原样完美工作。在横向 - 因为
aspectRatio设置为.fit- 图像的高度受到尊重,而两侧的蓝色边框是因为图像方面未设置为填充。我没有看到您发布的代码有任何问题。您可以在真实设备上或(至少)在模拟器中尝试吗?也许你的问题是PreviewProvider。 -
我在真机(iphone XS Max)上试过了,结果和模拟器一样。