Search code examples
iosswiftuiopacity

Applying opacity to ZStack in SwiftUI


Here is my code of two overlapping rects, with opacity applied to them.

var body: some View {
    let r = Rectangle()
        .foregroundColor(.blue)
        .frame(width: 80, height: 40)
        .position(x: 60, y: 110)

    let r2 = Rectangle()
        .foregroundColor(.green)
        .frame(width: 80, height: 40)
        .position(x: 70, y: 120)

    return ZStack {
        r
        r2
    }.opacity(0.5)
}

They look like this:

They need to look like this (red rect just to see opacity better):

So what I'm saying is the blue rect should not be visible under the green one. Because the opacity should be applied to them both as a group, not individually to each of them one by one. How can I achieve that?


Solution

  • Use compositing group before opacity modifier, like

    demo

    return ZStack {
        r
        r2
    }
    .compositingGroup()    // << here !!
    .opacity(0.5)