Home > Mobile >  SwiftUI, add inverted Opacity
SwiftUI, add inverted Opacity

Time:11-29

Please see the attach image below, I want to the make this view in siwftUI that have zero opacity inside.

struct TestView: View {
    var body: some View {
        ZStack{

//            any dummy image
            Image("bigpancake")
                .resizable()

            ZStack {
                
//                Make this view opcity zero so that I can see backgourd clearly
                Rectangle()
                    .frame(width: 200, height: 100)
                    .foregroundColor(.black.opacity(0))

                
                Rectangle()
                .foregroundColor(.black.opacity(0.3))
                
            }
            
        }
    }
    
}

enter image description here

CodePudding user response:

If I understand correctly what you are looking for, it sounds like an "inverted mask". You can achieve what you want using compositingGroup()

Example:

struct ContentView: View {
    var body: some View {
        ZStack {
            Image("background")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .ignoresSafeArea()
            ZStack {
                Rectangle()
                    .foregroundColor(.black.opacity(0.3))
                    .ignoresSafeArea()

                Rectangle()
                    .cornerRadius(20)
                    .frame(width: 200, height: 200)
                    .blendMode(.destinationOut)
                    .overlay {
                        Text("Content")
                    }
            }.compositingGroup()
        }
    }
}

enter image description here

  • Related