🔹veiw.compositingGroup()
SwiftUI ⟩ view ⟩ drawing ⟩ .compositingGroup()
- shadow:如果要幫整個 container view 加陰影,需用到 - .compositingGroup()。
- 在 even-odd fill mode 使用的例子中,如果沒用 - .compositingGroup(),連挖空的部分都會有影子。

import SwiftUI
typealias HA = HorizontalAlignment
typealias VA = VerticalAlignment
let w: CGFloat = 100
let h: CGFloat = 50
let r1 = Rectangle().padding(1).frame(w, h).foregroundColor(.pink)
let r2 = Rectangle().padding(1).frame(h, w).foregroundColor(.blue)
struct MyRects: 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] }
        }// VStack (container)
        .aspectRatio(1, contentMode: .fit)
    }
}
// live view
struct ContentView: View {
    var body: some View {
        HStack {
            MyRects()                // ⭐️ 不同圖層,影子會有層次感
            MyRects()
                .compositingGroup()  // ⭐️ 變為同一圖層
        }// HStack
            .padding()
            .shadow(color: .black, radius: 4, x: 4, y: 4)
            .background(Color.gray)
    }
}Last updated
Was this helpful?