web-dev-qa-db-ja.com

SWIFTUI:画像()が画面の境界の外側の範囲の展開を防ぐ

私が達成しようとしていること

画像が画面全体(edgesIgnoringSafeArea(.all))を展開する必要があるSwiftuiビューを作成し、その上にビューをオーバーレイしてから、画面全体を埋めますが、安全な領域を尊重します。

試したもの

これは私のコードです。

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

問題とテストされたソリューション

この問題は、イメージがクリップされていないことです。そのため、親ビューを画面幅よりも大きい幅に展開します。これにより、上部右向きの赤テキストボックスが画面からFloat Off Screat(イメージを参照)になります。

enter image description here

私は様々な場所で.clipped()を使ってみました。可能であれば、GeometryReaderを使用しないようにします。

Q:イメージビューを画面に埋めるだけですか。

10
eivindml

範囲外画像のフレームサイズを制限する必要があります。 zstackzStackを避けるために( - === - )成長するためにオーバーレイ位置から外れる。

親ビューのサイズに基づいています

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

Example

5
Fabian