Mar*_*rga 5 swift swiftui vstack
我正在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)
}
}
Run Code Online (Sandbox Code Playgroud)
当我.frame (width: geometry.size.width)通过分配的宽度使用时geometry,该宽度会显示在整个屏幕上,但高度不能保持纵横比。(看起来被压碎了)
如何获取图像的尺寸并找到其比例以用于 .aspectRatio (myratio, contentMode: .fit)
还有另一种正确显示图像的方法,任何建议
您需要消除第二个GeometryReader,因为有两个孩子都VStack接受所提供的尽可能多的空间将使他们无法VStack提供Image正确的空间量。
您还需要提高 的布局优先级,Image以便VStack首先为其提供空间,这样它就可以占用所需的空间。
import SwiftUI
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()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.blue))
.padding()
Image(uiImage: UIImage(named: "sample")!)
.resizable()
.aspectRatio(contentMode: .fit)
.layoutPriority(1)
}
}
}
import PlaygroundSupport
let host = UIHostingController(rootView: ContentView())
host.preferredContentSize = .init(width: 414, height: 896)
PlaygroundPage.current.liveView = host
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |