示例工程 54-ios-app-anatomy
54-ios-app-anatomy/Sources/Ch54Demo/App.swift
import AppKit
import Ch54Kit
import SwiftUI
@main
struct Ch54Demo {
@MainActor
static func main() {
print("[54.1] macOS 菜单栏 = \(PlatformProfile.macOS.menuBar)")
print("[54.2] iOS 多窗口 = \(PlatformProfile.iOS.multipleWindows)")
print("[54.3] iOS 最低系统 = \(PlatformProfile.iOS.minimumSystem)")
let bounds = CGRect(x: 0, y: 0, width: 390, height: 844)
let content = SafeArea.phoneWithNotch.contentRect(in: bounds)
print("[54.4] 内容高度 = \(Int(content.height))")
print("[54.5] 内容宽度 = \(Int(content.width))")
var state = AppState.notRunning
for event in [AppEvent.launch, .activate, .deactivate, .background, .foreground] {
state = Lifecycle.reduce(state, event)
}
print("[54.6] 最终状态 = \(state.rawValue)")
print("[54.7] 可动画 = \(Lifecycle.canAnimate(state))")
print("[54.8] 解剖板渲染 = \(size(AnatomyBoard()))")
print("[54.9] MemoryLayout<SafeArea> = \(MemoryLayout<SafeArea>.size) 字节")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(AnatomyBoard(), name: "ios-anatomy-board.png", directory: directory)
}
}
@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("[54.10] 截图失败:\(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("[54.10] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[54.10] 截图失败:\(error)")
}
}
}