【问题标题】:SwiftUI fullscreen image backgroundSwiftUI 全屏图片背景
【发布时间】:2019-12-30 03:23:10
【问题描述】:

我想在背景中有一个全屏图像。我已经实现了这个:

struct LoginView: View {
    var body: some View {
        VStack {
            Spacer();
            Text("Hallo");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Spacer();
            }.background(Image("Background LaunchScreen")
                .resizable()
                .aspectRatio(UIImage(named: "Background LaunchScreen")!.size, contentMode: .fill)
                .clipped())
            .edgesIgnoringSafeArea(.all)
    }
}

移除垫片后,图像不再以全屏模式显示。
确定可以用不同的方式解决吗?

如果我将模拟器中的 iPhone 转到一边,我会出现左右白色条纹。
我该如何更改?

【问题讨论】:

    标签: image background swiftui


    【解决方案1】:

    这是使用GeometryReaderZStack 的可能解决方案:

    import SwiftUI
    
    struct LoginView: View {
        var body: some View {
            GeometryReader { geometry in
                ZStack {
                    Image("LaunchImage")
                        .resizable()
                        .aspectRatio(geometry.size, contentMode: .fill)
                        .edgesIgnoringSafeArea(.all)
                    VStack {
                        ForEach (1...10, id: \.self) { _ in
                            Text("Hallo")
                                .foregroundColor(Color.white)
                        }
                    }
                }
            }
        }
    }
    
    #if DEBUG
    struct LoginView_Previews: PreviewProvider {
        static var previews: some View {
            LoginView()
        }
    }
    #endif
    

    结果

    【讨论】:

    • 上面的解决方案对我有用,你能告诉我为什么你使用 GeometryReader 然后 ZStack 因为我也尝试了下面的代码 ZStack { Image("bgImg") .resizable() .scaledToFill() .edgesIgnoringSafeArea (.all) } 这对我有用,所以有什么不同
    • @Dilip 当时(2019 年 8 月 25 日),这是我让它工作的唯一方法。如果它现在可以在没有GeometryReader 的情况下工作,那就更好了。 :)
    • 非常感谢我只使用您的答案,感谢您的回复
    • 这会使图像增加 ZStack,如果我将某些东西向左对齐,它会从屏幕外开始
    【解决方案2】:

    这应该可以在没有 GeometryReader 的情况下工作:

    var body: some View {
           ZStack {
                ZStack {}
                .frame( maxWidth: .infinity, maxHeight: .infinity)
                .background(Image("Background LaunchScreen").resizable())
                .ignoresSafeArea()
                VStack {
                    Text("Text")
                    Text("Text")
                    Text("Text")
                    Text("Text")
                    Spacer()
                }
            }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2017-10-07
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多