英文:
SwiftUI: How to let a view extend past safe area and center between screen to and bottom?
问题
我有类似以下的代码:
var body: some View
{
VStack
{
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
}
}
我的图片具有1:1的宽高比。在iPhone上,这意味着没有足够的垂直空间来容纳它们。
目前,这些图片在垂直方向上被压缩。
如何确保这三个图像都填充屏幕的宽度,中间的图像居中显示,并且顶部和底部的图像延伸超出屏幕的顶部和底部边缘?
英文:
I have code that's similar to:
var body: some View
{
VStack
{
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
Image("someImage")
.resizable()
.frame(width: UIScreen.main.bounds.width)
}
}
My image has a 1:1 aspect ratio. On iPhone this would mean that there's not enough vertical space to fit them.
Currently the images are vertically compressed.
How can I make sure that all three images fill the width of the screen, that the middle image is centered, and that the top and bottom images extend past the top and bottom edges of the screen?
答案1
得分: 1
resizable
修饰符将告诉图像填充其父级的空间,而不关心原始纵横比例。
你想要的是强制图像保持其纵横比,同时占用所有可用空间(contentMode: .fill
):
Image(systemName: "someImage")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: UIScreen.main.bounds.width)
如果你在VStack
中放置的项多于屏幕上可见的数量,那么内容将已经超出屏幕(和安全区域)的边界,除非内容明确调整大小以适应其父级。
你可以通过将contentMode
更改为.fit
来查看此行为。
适应 | 填充 |
---|---|
英文:
The resizable
modifier will tell the image to fill the space of its parent without caring about the original aspect ratio.
What you want is to force the image to maintain its aspect ratio, while occupying all available space (contentMode: .fill
):
Image(systemName: "someImage")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: UIScreen.main.bounds.width)
If you place more items in a VStack
than is visible on screen, the contents will already extend past the bounds of the screen (and the safe area), unless that content explicitly sizes to fit its parent.
You can see this behaviour by changing contentMode
to .fit
.
Fit | Fill |
---|---|
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论