Let the Shapes be on the same layer

Viewed 38

In the following code, the blue rectangles look like they're slightly "above" the red ones because of their shadows.

Is it possible to let them look like they are on the same layer, so that no one's shadow is on top of the others? Thanks.

four rectangles

import SwiftUI
import PlaygroundSupport

typealias HA = HorizontalAlignment
typealias VA = VerticalAlignment

let w: CGFloat = 200
let h: CGFloat = 100

let r1 = Rectangle().padding(1).frame(w, h).foregroundColor(.pink)
let r2 = Rectangle().padding(1).frame(h, w).foregroundColor(.blue)

// live view
struct ContentView: View {
    var body: some View {
        ZStack {
            r1
                .alignmentGuide(HA.center) { $0[.leading] }
                .alignmentGuide(VA.center) { $0[.bottom] }
            r1
                .alignmentGuide(HA.center) { $0[.trailing] }
                .alignmentGuide(VA.center) { $0[.top] }
            r2
                .alignmentGuide(HA.center) { $0[.trailing] }
                .alignmentGuide(VA.center) { $0[.bottom] }
            r2
                .alignmentGuide(HA.center) { $0[.leading] }
                .alignmentGuide(VA.center) { $0[.top] }
        }// ZStack (container)
            .padding()
            .shadow(color: .black, radius: 8, x: 8, y: 8)
            .background(Color.gray)
    }
}

PlaygroundPage.current.setLiveView(ContentView())
1 Answers

I assume you need composition group (so shadow applied to all rectangles at once, instead of by one)

    }// ZStack (container)
        .padding()
        .compositingGroup()    // << here !!
Related