2

I want to show text combine with Rectangle as below image. I have already draw it in sketch by Combined Shape of Difference mode. enter image description here

I code it in Xcode by SwiftUI, the code show as below:

struct DiffView: View {
    var body: some View {
        ZStack() {
            Rectangle()
                .fill(Color.blue)
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.blue)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .blendMode(.difference)
                .offset(x: 20, y: 0)
                
        }
        .frame(width: 100, height: 100, alignment: .center)
        .background(Color.white)
    }
}

But the result is not as expected as in Sketch, the overlapping part on the left becomes black (expected to be white), and the letter on the right becomes yellow (expected to be blue).

enter image description here

How should I use swiftui blendMode correctly?enter code here

New Dev
  • 48,427
  • 12
  • 87
  • 129
mars
  • 109
  • 5
  • 21

1 Answers1

3

It takes into account background, so diff blue from white gives orange. So at first let's remove background from blending by using compositingGroup

struct DiffView: View {
    var body: some View {
        ZStack() {
                Color.blue
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.blue)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .offset(x: 20, y: 0)
                .blendMode(.difference)
        }
        .compositingGroup()
        .frame(width: 100, height: 100, alignment: .center)
    }
}

which gives

demo1

Well it is because pure difference does not have anything in background and thus gives black color. So your effect can be achieved by the following

struct DiffView: View {
    var body: some View {
        ZStack() {
                Color.orange
                .frame(width: 50, height: 50, alignment: .center)
            Text("DIFF")
                .foregroundColor(Color.orange)
                .font(.system(size: 30, weight: .bold, design: .rounded))
                .offset(x: 20, y: 0)
                .blendMode(.difference)
        }
        .compositingGroup()
        .colorInvert()
        .frame(width: 100, height: 100, alignment: .center)
    }
}

demo2

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690