示例工程 37-animation

37-animation/Sources/Ch37Kit/Animation.swift

swift · 5.8 KB

import SwiftUI
 
/// 把弹簧参数抽成可测试的值:给定时间,返回归一化进度。
public struct SpringProbe: Sendable {
    public let spring: Spring
 
    public init(response: Double = 0.5, dampingRatio: Double = 0.8) {
        self.spring = Spring(response: response, dampingRatio: dampingRatio)
    }
 
    public func progress(at time: Double) -> Double {
        spring.value(target: 1, initialVelocity: 0, time: time)
    }
 
    public var settlingDuration: Double {
        spring.settlingDuration
    }
 
    /// 峰值是否超过 1(阻尼不足时会过冲)。
    public func overshoots(at time: Double) -> Bool {
        progress(at: time) > 1.0001
    }
}
 
/// 相位驱动的动画:idle → loading → done → idle。
public enum Phase: String, CaseIterable, Sendable {
    case idle
    case loading
    case done
 
    public var next: Phase {
        switch self {
        case .idle: .loading
        case .loading: .done
        case .done: .idle
        }
    }
}
 
/// 一个用显式动画驱动的展开卡片。
public struct ExpandingCard: View {
    @State private var expanded = false
 
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Button(expanded ? "收起" : "展开") {
                withAnimation(.spring(response: 0.35, dampingFraction: 0.75)) {
                    expanded.toggle()
                }
            }
            .buttonStyle(.bordered)
 
            if expanded {
                Text("显式动画只影响这次状态变化引发的差值。")
                    .font(.system(size: 12))
                    .transition(.opacity.combined(with: .move(edge: .top)))
            }
        }
        .padding(16)
        .frame(width: 300, alignment: .leading)
        .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
    }
}
 
/// 进度条:宽度由进度驱动,配合 `.animation(_:value:)` 做隐式动画。
public struct ProgressBar: View {
    public let progress: Double
 
    public init(progress: Double) {
        self.progress = progress
    }
 
    public var body: some View {
        GeometryReader { proxy in
            ZStack(alignment: .leading) {
                Capsule().fill(.quaternary)
                Capsule()
                    .fill(
                        LinearGradient(
                            colors: [.blue, .cyan],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .frame(width: max(0, min(1, progress)) * proxy.size.width)
            }
        }
        .frame(height: 10)
    }
}
 
/// 截图板:弹簧曲线、进度条、相位徽章。
public struct AnimationBoard: View {
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("弹簧曲线")
                .font(.system(size: 11, design: .monospaced))
                .foregroundStyle(.secondary)
            SpringCurve(probe: SpringProbe())
                .frame(width: 320, height: 110)
                .border(.quaternary)
 
            Text("进度 72%")
                .font(.system(size: 11, design: .monospaced))
                .foregroundStyle(.secondary)
            ProgressBar(progress: 0.72)
 
            HStack(spacing: 8) {
                ForEach(Phase.allCases, id: \.self) { phase in
                    Text(phase.rawValue)
                        .font(.system(size: 11, design: .monospaced))
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(
                            phase == .loading ? Color.blue.opacity(0.2) : Color.gray.opacity(0.12),
                            in: Capsule()
                        )
                }
            }
        }
        .padding(18)
        .frame(width: 360, alignment: .leading)
        .background(Color.white)
    }
}
 
/// 用离散采样画弹簧曲线,便于截图说明「过冲」。
public struct SpringCurve: View {
    public let probe: SpringProbe
    public let samples: Int
 
    public init(probe: SpringProbe = SpringProbe(), samples: Int = 120) {
        self.probe = probe
        self.samples = samples
    }
 
    public var body: some View {
        Canvas { context, size in
            var path = Path()
            for index in 0...samples {
                let t = Double(index) / Double(samples) * 1.2
                let value = min(max(probe.progress(at: t), 0), 1.2)
                let point = CGPoint(
                    x: CGFloat(index) / CGFloat(samples) * size.width,
                    y: size.height - CGFloat(value / 1.2) * size.height
                )
                if index == 0 {
                    path.move(to: point)
                } else {
                    path.addLine(to: point)
                }
            }
            context.stroke(path, with: .color(.blue), lineWidth: 2)
            let baseline = Path(
                CGRect(x: 0, y: size.height * (1 - 1 / 1.2), width: size.width, height: 1))
            context.fill(baseline, with: .color(.gray.opacity(0.35)))
        }
        .background(Color.white)
    }
}
 
/// 截图:展开态的静态卡片(关键帧)。
public struct ExpandedCardBoard: View {
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("收起")
                .font(.system(size: 11, design: .monospaced))
                .padding(.horizontal, 8)
                .padding(.vertical, 3)
                .background(.quaternary, in: Capsule())
            Text("显式动画只影响这次状态变化引发的差值。")
                .font(.system(size: 12))
        }
        .padding(16)
        .frame(width: 320, alignment: .leading)
        .background(Color.white, in: RoundedRectangle(cornerRadius: 12))
    }
}