SwiftUI:防止 Image() 在屏幕边界之外扩展视图矩形 [英] SwiftUI: Prevent Image() from expanding view rect outside of screen bounds
问题描述
我正在尝试创建一个 SwiftUI 视图,其中图像应扩展整个屏幕 (edgesIgnoringSafeArea(.all)
),然后在其上叠加一个视图,该视图也填充整个屏幕屏幕,但尊重安全区域.
I'm trying to create a SwiftUI view where an image should expand the entire screen (edgesIgnoringSafeArea(.all)
), and then overlay a view on top of that, that also fills the entire screen, but respects the safe area.
这是我的代码,很接近:
This is my code, which comes close:
struct Overlay: View {
var body: some View {
VStack {
HStack {
EmptyView()
Spacer()
Text("My top/right aligned view.")
.padding()
.background(Color.red)
}
Spacer()
HStack {
Text("My bottom view")
.padding()
.background(Color.pink)
}
}
}
}
struct Overlay_Previews: PreviewProvider {
static var previews: some View {
ZStack {
Image(uiImage: UIImage(named: "background")!)
.resizable()
.edgesIgnoringSafeArea(.all)
.aspectRatio(contentMode: .fill)
Overlay()
}
}
}
问题和经过测试的解决方案
问题是图像没有像看起来那样被剪裁,因此它将父视图扩展到大于屏幕宽度的宽度,然后使右上方对齐的红色文本框浮出屏幕(见图).
The issue and tested solutions
The issue is that the image is not clipped it looks like, so it expands the parent view to a width larger than the screen width, which then makes the top right aligned red text box float off screen (see image).
我尝试在不同的地方使用 .clipped()
,但没有成功.如果可能,我最好避免使用 GeometryReader
.
I tried using .clipped()
in various places, with no luck. I would preferably avoid using GeometryReader
if possible.
推荐答案
你必须限制越界图像的帧大小,在它被拾取之前ZStack 以避免 ZStack 增长,从而使 Overlay 失去位置.
You have to limit the frame size of the out-of-bounds Image before it is being picked up by the ZStack to avoid the ZStack to grow and so the Overlay to go out of position.
struct IgnoringEdgeInsetsView2: View {
var body: some View {
ZStack {
GeometryReader { geometry in
Image("smile")
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: geometry.size.width,
maxHeight: geometry.size.height)
}
Overlay()
}
}
}
基于屏幕尺寸
struct IgnoringEdgeInsetsView: View {
var body: some View {
ZStack {
Image("smile-photo")
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
.frame(maxWidth: UIScreen.main.bounds.width,
maxHeight: UIScreen.main.bounds.height)
Overlay()
}
}
}
这篇关于SwiftUI:防止 Image() 在屏幕边界之外扩展视图矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!