示例工程 37-animation
37-animation/Sources/Ch37Demo/App.swift
import AppKit
import Ch37Kit
import SwiftUI
@main
struct Ch37Demo {
@MainActor
static func main() {
let probe = SpringProbe(response: 0.5, dampingRatio: 0.8)
print("[37.1] t=0 进度 = \(format(probe.progress(at: 0)))")
print("[37.2] t=0.25 进度 = \(format(probe.progress(at: 0.25)))")
print("[37.3] t=10 进度 = \(format(probe.progress(at: 10)))")
print("[37.4] t=0.5 过冲 = \(probe.overshoots(at: 0.5))")
print("[37.5] 稳定时间 = \(format(probe.settlingDuration))")
var phase = Phase.idle
var chain: [String] = [phase.rawValue]
for _ in 0..<3 {
phase = phase.next
chain.append(phase.rawValue)
}
print("[37.6] 相位序列 = \(chain.joined(separator: " → "))")
print("[37.7] 动画板渲染 = \(size(AnimationBoard()))")
print("[37.8] MemoryLayout<SpringProbe> = \(MemoryLayout<SpringProbe>.size) 字节")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(AnimationBoard(), name: "animation-board.png", directory: directory)
}
}
private static func format(_ value: Double) -> String {
String(format: "%.3f", value)
}
@MainActor
private static func size(_ view: some View) -> String {
guard let image = ImageRenderer(content: view).cgImage else { return "nil" }
return "\(image.width)x\(image.height)"
}
@MainActor
private static func write(_ view: some View, name: String, directory: String) {
let renderer = ImageRenderer(content: view)
renderer.scale = 2
guard
let image = renderer.cgImage,
let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
else {
print("[37.9] 截图失败:\(name)")
return
}
let url = URL(fileURLWithPath: directory).appendingPathComponent(name)
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try data.write(to: url)
print("[37.9] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[37.9] 截图失败:\(error)")
}
}
}