示例工程 34-drawing-shapes-canvas
34-drawing-shapes-canvas/Sources/Ch34Demo/App.swift
import AppKit
import Ch34Kit
import SwiftUI
@main
struct Ch34Demo {
@MainActor
static func main() {
let rect = CGRect(x: 0, y: 0, width: 100, height: 40)
let path = ChartGeometry.path(values: [0, 0.5, 1], in: rect)
let box = path.boundingRect
print("[34.1] Path 包围盒 = (\(box.minX), \(box.minY), \(box.width), \(box.height))")
print(
"[34.2] Canvas 青色像素 = \(cyanCount(ParticleField(time: 0.4).frame(width: 120, height: 120)))"
)
print("[34.3] Circle 渲染 = \(text(Circle().fill(.blue).frame(width: 40, height: 40)))")
let chart = LineChart(values: [0.1, 0.4, 0.25, 0.7, 0.55, 0.9, 0.65])
.frame(width: 320, height: 180)
print("[34.4] 图表导出 = \(text(chart))")
print("[34.5] MemoryLayout<ChartShape> = \(MemoryLayout<ChartShape>.size) 字节")
probeCount()
let stroked = Rectangle().stroke(.red, lineWidth: 10).frame(width: 40, height: 40)
print("[34.8] 描边内侧像素 = \(sample(stroked, x: 2, y: 20))")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(DrawingBoard(), name: "drawing-board.png", directory: directory)
write(chart, name: "chart.png", directory: directory)
}
}
@MainActor
private static func size(_ view: some View) -> CGSize {
guard let image = ImageRenderer(content: view).cgImage else { return .zero }
return CGSize(width: image.width, height: image.height)
}
@MainActor
private static func text(_ view: some View) -> String {
let value = size(view)
return "\(Int(value.width))x\(Int(value.height))"
}
@MainActor
private static func cyanCount(_ view: some View) -> Int {
guard let image = ImageRenderer(content: view).cgImage else { return -1 }
let rep = NSBitmapImageRep(cgImage: image)
var count = 0
for x in stride(from: 0, to: image.width, by: 2) {
for y in stride(from: 0, to: image.height, by: 2) {
guard let color = rep.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) else { continue }
if color.greenComponent > 0.5, color.blueComponent > 0.5, color.redComponent < 0.4 {
count += 1
}
}
}
return count
}
@MainActor
private static func sample(_ view: some View, x: Int, y: Int) -> String {
guard
let image = ImageRenderer(content: view).cgImage,
let color = NSBitmapImageRep(cgImage: image).colorAt(x: x, y: y)?.usingColorSpace(.sRGB)
else {
return "nil"
}
return String(format: "a=%.2f", color.alphaComponent)
}
@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("[34.6] 截图失败:\(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("[34.6] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[34.6] 截图失败:\(error)")
}
}
}