Search code examples
swiftswiftui

Blendmode with Text view making overlapping area white and rest as black


I'm trying to make a text view that switch colors to white for the region that's overlapping with another view and rest of it in black.

Below is the code tryout following this question which uses blend mode but it makes the overlapped region green and it's based on the background view color. I want it as always white irrespective of the overlapping view color and rest of the text view in black.

struct ContentView: View {
    var body: some View {
        ZStack() {
            Color.purple.frame(width: 200, height: 40, alignment: .center)
                .offset(x: 0, y: 20)

            Text("Over")
                .foregroundColor(Color.white)
                .font(.system(size: 55, weight: .bold, design: .rounded))
                .offset(x: 10, y: 0)
                .blendMode(.difference)

        }
        .frame(width: 200, height: 100, alignment: .center)
    }
}

screenshot of the current result


Solution

  • Use 2 Texts and a mask instead.

    struct ContentView: View {
        var body: some View {
            ZStack {
                Color.purple
                    .frame(width: 200, height: 40, alignment: .center)
                    .offset(x: 0, y: 20)
    
                Text("Over")
                    .foregroundColor(Color.black)
                    .font(.system(size: 55, weight: .bold, design: .rounded))
                    .offset(x: 10, y: 0)
    
                Text("Over")
                    .foregroundColor(Color.white)
                    .font(.system(size: 55, weight: .bold, design: .rounded))
                    .offset(x: 10, y: 0)
                    .mask(Rectangle().frame(height: 20).offset(x: 0, y: 10))
    
            }
            .frame(width: 200, height: 100, alignment: .center)
        }
    }
    

    Result:

    screenshot of the result