even-odd fill mode

⬆️ 需要:

import SwiftUI
import Vector2D        // for 🌀Rectangular

struct EOFillShape: Shape {
    
    // ⭐ 要畫幾層的線
    let layers: Int
    
    func path(in rect: CGRect) -> Path {
        let dx = pad(rect)            // 計算內縮的量
        return Path { path in
            for i in 0..<layers {
                // 🌀CGRect + .inset(by:), 🌀Int+
                path.addRect(rect.inset(by: dx * i))
            }
        }
    }
}

extension EOFillShape {
    // 計算每次內縮 (inset) 的量
    func pad(_ rect: CGRect) -> CGFloat {
        // 🌀Rectangular, 🌀Int+
        let padding = rect.minSide / 2.0 / layers
        return min(20, padding)    // 不超過 20
    }
}

struct EOFillShape_Previews: PreviewProvider {
    static var previews: some View {
        HStack {
            ForEach(1..<6){ i in
                let shape = EOFillShape(layers: i)
                let black = Color.black
                VStack {
                    shape
                    
                        // ⭐ use even-odd fill mode
                        // 🌀ShapeStyle+ , FillStyle+
                        .fill(.diagonal(.green, .blue), style: .evenOddFill)
                        
                        // ⭐ 如果沒有 compositingGroup,整塊都會有陰影❗
                        .compositingGroup()
                        
                        .shadow(radius: 8)
                        .overlay(shape.stroke(black))
                    shape
                        // 🌀ShapeStyle+
                        .fill(.diagonal2(.pink, .purple, .blue))
                        .shadow(radius: 8)
                        .overlay(shape.stroke(black))
                }
            }
        }
        .frame(height: 200)
        .padding()
        .background(Color.gray)
    }
}

Last updated