示例工程 34-drawing-shapes-canvas

34-drawing-shapes-canvas/Sources/Ch34Kit/Drawing.swift

swift · 4.6 KB

import SwiftUI
 
/// 纯几何:把 0...1 的数据映射到给定矩形,返回折线路径。
public enum ChartGeometry {
    public static func path(values: [Double], in rect: CGRect) -> Path {
        var path = Path()
        guard values.count > 1 else { return path }
        let stepX = rect.width / CGFloat(values.count - 1)
        for (index, value) in values.enumerated() {
            let clamped = min(max(value, 0), 1)
            let point = CGPoint(
                x: rect.minX + CGFloat(index) * stepX,
                y: rect.maxY - CGFloat(clamped) * rect.height
            )
            if index == 0 {
                path.move(to: point)
            } else {
                path.addLine(to: point)
            }
        }
        return path
    }
}
 
/// `Shape` 版本:参与动画与描边。
public struct ChartShape: Shape {
    public var values: [Double]
 
    public init(values: [Double]) {
        self.values = values
    }
 
    public func path(in rect: CGRect) -> Path {
        ChartGeometry.path(values: values, in: rect)
    }
}
 
/// 折线图:描边 + 渐变填充。
public struct LineChart: View {
    public let values: [Double]
 
    public init(values: [Double]) {
        self.values = values
    }
 
    public var body: some View {
        ZStack {
            ChartShape(values: values)
                .fill(
                    LinearGradient(
                        colors: [.blue.opacity(0.35), .blue.opacity(0.02)],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
            ChartShape(values: values)
                .stroke(.blue, style: StrokeStyle(lineWidth: 2, lineJoin: .round))
        }
        .padding(6)
    }
}
 
/// 画布:即时绘制,不参与视图树。粒子位置由索引与时间决定,结果确定。
public struct ParticleField: View {
    public let time: Double
 
    public init(time: Double) {
        self.time = time
    }
 
    public var body: some View {
        Canvas { context, size in
            context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.black.opacity(0.9)))
            for index in 0..<24 {
                let angle = Double(index) / 24 * Double.pi * 2 + time
                let radius = 18.0 + Double(index % 5) * 4
                let x = size.width / 2 + cos(angle) * radius
                let y = size.height / 2 + sin(angle) * radius
                let rect = CGRect(x: x - 1.5, y: y - 1.5, width: 3, height: 3)
                context.fill(Path(ellipseIn: rect), with: .color(.cyan))
            }
        }
    }
}
 
/// 简单渐变徽章,用于截图。
public struct GradientBadge: View {
    public init() {}
 
    public var body: some View {
        HStack(spacing: 10) {
            Circle()
                .fill(
                    LinearGradient(
                        colors: [.blue, .purple],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .frame(width: 36, height: 36)
            VStack(alignment: .leading, spacing: 2) {
                Text("Shape + Canvas").font(.system(size: 14, weight: .semibold))
                Text("矢量描述 vs 即时绘制").font(.system(size: 11)).foregroundStyle(.secondary)
            }
        }
        .padding(12)
        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
    }
}
 
/// 截图板:折线、粒子、徽章。
public struct DrawingBoard: View {
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            LineChart(values: [0.1, 0.4, 0.25, 0.7, 0.55, 0.9, 0.65])
                .frame(width: 280, height: 110)
                .border(.quaternary)
            ParticleField(time: 0.4)
                .frame(width: 280, height: 110)
                .clipShape(RoundedRectangle(cornerRadius: 8))
            GradientBadge()
        }
        .padding(16)
        .background(Color.white)
    }
}
 
/// 记录 `path(in:)` 被调用的次数。
public struct CountingShape: Shape {
    public let counter: PathCounter
    public let radius: CGFloat
 
    public init(counter: PathCounter, radius: CGFloat = 10) {
        self.counter = counter
        self.radius = radius
    }
 
    public func path(in rect: CGRect) -> Path {
        counter.count += 1
        return Path(
            ellipseIn: CGRect(
                x: rect.midX - radius,
                y: rect.midY - radius,
                width: radius * 2,
                height: radius * 2
            ))
    }
}
 
public final class PathCounter: @unchecked Sendable {
    public var count = 0
 
    public init() {}
}