首页 > 解决方案 > SwiftUI:防止 Image() 将视图矩形扩展到屏幕边界之外

问题描述

我想要达到的目标

我正在尝试创建一个 SwiftUI 视图,其中图像应该扩展整个屏幕(edgesIgnoringSafeArea(.all)),然后在其上覆盖一个视图,该视图也填充整个屏幕,但尊重安全区域。

我试过的

这是我的代码,接近:

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()
    }
  }
}

问题和经过测试的解决方案

问题是图像没有像看起来那样被剪裁,因此它将父视图扩展为大于屏幕宽度的宽度,然后使右上角对齐的红色文本框浮出屏幕(见图)。

在此处输入图像描述

我尝试.clipped()在各个地方使用,但没有运气。如果可能的话,我最好避免使用GeometryReader

问:如何让图像视图只填满屏幕?

标签: swiftswiftui

解决方案


在ZStack拾取越界Image之前,您必须限制其帧大小,以避免ZStack增长,从而导致Overlay偏离位置。

编辑: aheze 用他的答案展示了一种GeometryReader通过将withImage放入背景来Overlay()使用的方法.background(Image()..)。这完全避免了和的使用,ZStack并且GeometryReader可能是一种更清洁的解决方案。

基于父视图大小

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()
        }
    }
}

例子


推荐阅读