iosswiftuibackground

How to create a dim background using the SwiftUI


I want to create a dim background that looks like the following picture, but it has a slight green tint to it.

This is my code:

import SwiftUI

struct DimBackgroundView: View {
    var body: some View {
        VStack {
            Spacer()
            
            VStack {
                Text("Dim background")
            }
            .frame(height: 350)
            .frame(maxWidth: .infinity)
            .background(.green) // <- Not work
            .background(.ultraThinMaterial)
            .cornerRadius(30)
        }
        .ignoresSafeArea()
//        .background(.green) // <- Not work
    }
}

struct DimBackgroundVie_Previews: PreviewProvider {
    static var previews: some View {
        DimBackgroundView()
    }
}

Result:

enter image description here

My expected:

enter image description here

I tries adding a green background before but it didn't work. Does anyone have a solution for it?


Solution

  • You can archive this by using the ZStack or Overlay function to make the background image or color blurred or appear as a ThinMaterial.

    Below, I'll provide answers to your question:

    struct DimBackgroundView: View {
        var body: some View {
            VStack {
                Spacer()
                
                ZStack {
                    //              Color.green
                    Image("kenny-s-7qRM11Kmnh4-unsplash")
                    
                    Text("Click me")
                        .frame(width: UIScreen.main.bounds.width, height: 350, alignment: .center)
                        .background(.ultraThinMaterial)
                }
                .frame(height: 350)
                .cornerRadius(30)
            }
            .ignoresSafeArea()
        }
    }
    

    Here, I'm using ZStack to make the background appear as ThinMaterial or blur.

    Output :

    https://www.linkpicture.com/q/Screenshot-2023-04-01-at-12.20.49-PM.png