🅿️Shape
╱🚧 under construction -> Canvas, Shape 必須具備甚麼特質?
SwiftUI ⟩ shapes ⟩ Shape (protocol)
 
 Shape is a "push-out" view.
// protocol definition
protocol Shape : Sendable, Animatable, View, _RemoveGlobalActorIsolationIf you need the efficiency or flexibility of immediate mode drawing — for example, to create particle effects — use a Canvas view instead.
- Polygon - an animatable polygon shape. 

- SwiftUI ⟩ 
- SwiftOnTap ⟩ View ⟩ .clipShape(_:style:) → some View 
- Shape:shape.fill(content) 的填充樣式 content 是 ShapeStyle。 
- inherits from View, Animatable. 
- Path conforms to Shape. 
- can have animations. 
- can be filled. 
- can be clipped using even-odd fill mode. 
Examples

import SwiftUI
import PlaygroundSupport
// ContentView
struct ContentView: View {
    
    // body
    var body: some View {
        VStack{
            hstack1
            hstack2
        }.padding()
    }
    
    var hstack1: some View {
        HStack{
            Group{
                Triangle()
                    .stroke()
                Triangle()
                    .fill(Color.red)
                Triangle()
                    .stroke(Color.red, style: StrokeStyle(lineWidth: 10, lineCap: .round, lineJoin: .round))
                Arc(start: 110, end: 0, clockwise: true)
                    .stroke(lineWidth: 10)
                    .stroke(lineWidth: 5)
                    .stroke()
            }
            .frame(width: 100, height: 100)
            .border(Color.orange)
        }
    }
    
    var hstack2: some View {
        HStack{
            Group{
                Arc(start: 90, end: 0, clockwise: true)
                    .stroke(Color.blue, lineWidth: 20)
                Arc(start: 0, end: 270, clockwise: true)
                    .stroke(Color.pink, lineWidth: 8)
            }
            .frame(width: 208, height: 100)
            .border(Color.yellow)
        }
    }
}
PlaygroundPage.current.setLiveView(ContentView())import SwiftUI
import Vector2D    // for API: rect.center ...
struct Arc: Shape {
    
    var start: Double  // in degrees
    var end: Double    // in degrees
    var clockwise: Bool
    
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.addArc(
                center: rect.center, 
                radius: rect.minSide / 2, 
                startAngle: .degrees(start), 
                endAngle: .degrees(end), 
                clockwise: !clockwise
            )
        }
    }
}import SwiftUI
import Vector2D    // for API: rect.top ...
struct Triangle: Shape {
    func path(in rect: CGRect) -> Path { 
        Path { path in
            path.move(to: rect.top)
            path.addLine(to: rect.bottomLeft)
            path.addLine(to: rect.bottomRight)
            path.addLine(to: rect.top)
        }
    }
}範例
Last updated
Was this helpful?