Files
tinystt/scripts/make-icon.swift
T

65 lines
2.7 KiB
Swift

#!/usr/bin/env swift
// Package the TinySTT T-monogram source into all macOS icon sizes.
// Usage: swift scripts/make-icon.swift Resources
import AppKit
import Foundation
// MARK: - 输出
let outDir = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "Resources"
let fm = FileManager.default
let iconset = (outDir as NSString).appendingPathComponent("AppIcon.iconset")
let sourceURL = URL(fileURLWithPath: outDir).appendingPathComponent("AppIcon-source.png")
guard let source = NSImage(contentsOf: sourceURL) else {
fatalError("缺少图标源文件:\(sourceURL.path)")
}
try? fm.removeItem(atPath: iconset)
try fm.createDirectory(atPath: iconset, withIntermediateDirectories: true)
let variants: [(String, Int)] = [
("icon_16x16", 16), ("icon_16x16@2x", 32),
("icon_32x32", 32), ("icon_32x32@2x", 64),
("icon_128x128", 128), ("icon_128x128@2x", 256),
("icon_256x256", 256), ("icon_256x256@2x", 512),
("icon_512x512", 512), ("icon_512x512@2x", 1024),
]
for (name, px) in variants {
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,
isPlanar: false, colorSpaceName: .deviceRGB,
bytesPerRow: 0, bitsPerPixel: 0)!
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
NSGraphicsContext.current?.imageInterpolation = .high
source.draw(in: NSRect(x: 0, y: 0, width: px, height: px),
from: .zero, operation: .copy, fraction: 1)
NSGraphicsContext.restoreGraphicsState()
guard let data = rep.representation(using: .png, properties: [:]) else {
FileHandle.standardError.write("生成 \(name) 失败\n".data(using: .utf8)!)
exit(1)
}
try data.write(to: URL(fileURLWithPath: iconset).appendingPathComponent("\(name).png"))
}
let icns = (outDir as NSString).appendingPathComponent("AppIcon.icns")
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil")
proc.arguments = ["-c", "icns", iconset, "-o", icns]
try proc.run()
proc.waitUntilExit()
// 留一份 1024 PNG,供文档 / 网页 / 预览使用
try? fm.removeItem(atPath: (outDir as NSString).appendingPathComponent("AppIcon-1024.png"))
try? fm.copyItem(
atPath: (iconset as NSString).appendingPathComponent("icon_512x512@2x.png"),
toPath: (outDir as NSString).appendingPathComponent("AppIcon-1024.png")
)
guard proc.terminationStatus == 0 else {
FileHandle.standardError.write("iconutil 失败:\(proc.terminationStatus)\n".data(using: .utf8)!)
exit(1)
}
print("已生成 \(icns)")