SwiftUI:动态设置图像的大小 [英] SwiftUI: Dynamically set size for Image
问题描述
我想在视图中显示图像,其中图像源的大小会有所不同.有没有办法将图像的大小动态调整为包含视图的宽度或使屏幕大小均匀?我有一个水平滚动视图,每个元素都是一个图像和文本的堆栈.我想根据屏幕宽度调整每个图像的大小,因为我想独立于设备.你会如何在 SwiftUI 中做到这一点?谢谢!
I want to show an image in a View, where the image source will vary in size. Is there a way to dynamically adjust the size of the image to the width of the containing view or get the screen size even? I have a horizontal scrollview with each element being a Stack of an image and a text. I would like to size every image depending on the screen width, since I want to be independent of the device. How would you do that in SwiftUI? Thanks!
struct ImageRow: View {
var items: [ImageWithDescription]
var body: some View {
ScrollView(showsHorizontalIndicator: false) {
HStack(alignment: .bottom){
ForEach(self.items.identified(by: \.name)) { item in
Spacer()
VStack {
Image(uiImage: item.image ?? UIImage())
.resizable()
.frame(minWidth: (item.image.size.width) / 3, height: (item.image.size.height) / 3)
.cornerRadius(20, antialiased: true)
.clipShape(Rectangle())
.shadow(radius: 10)
Text(item.name)
.color(.primary)
.font(.subheadline)
}
}
.padding()
}
}
.frame(height: 300)
}
}
推荐答案
您可以获取屏幕(或窗口,如果您使用的是分屏 iPad)的大小.
You can get the size of the screen (or window, in case you are using an iPad with split screen).
在下面的示例中,顶视图使用 GeometryReader 获取大小并将其向下传递到层次结构.子视图使用该数据创建一个屏幕大小一半的蓝色矩形.如果设备旋转,它也会适应.
In the example below, the top view uses GeometryReader to get the size and passes it down the hierarchy. The subview uses that data to create a blue rectangle with half the size of the screen. It will also adapt if the device is rotated.
GeometryReader 有许多功能,虽然它们几乎没有记录,但我写了一篇文章充分解释了如何使用它们:https://swiftui-lab.com/geometryreader-to-the-rescue/
GeometryReader has many features, and although they are barely documented, I've written an article which fully explains how to use them: https://swiftui-lab.com/geometryreader-to-the-rescue/
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
MySubview(size: geometry.size)
}
}
}
struct MySubview: View {
let size: CGSize
var body: some View {
print("size = \(size)")
return Color.blue.frame(width: size.width / 2, height: size.height / 2).fixedSize()
}
}
这篇关于SwiftUI:动态设置图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!