Skip to content

Instantly share code, notes, and snippets.

@paulgalow
Last active January 15, 2018 18:44
Show Gist options
  • Save paulgalow/7b74740c2b166f1ec53a6190610464fb to your computer and use it in GitHub Desktop.
Save paulgalow/7b74740c2b166f1ec53a6190610464fb to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
import AppKit
func generateMacIcon(dimension: CGFloat, name iconName: String) {
// Make sure our maximum rendering size does not exceed 512 px
guard dimension <= 512 else {
print("Error: Maximum dimension allowed is 512")
return
}
// Make sure our minimum rendering size is greater than 0
guard dimension > 0 else {
print("Error: Please provide a non-negative dimension value")
return
}
// Try to create an NSImage of the computer model if not bail out
guard let image = NSImage(named: NSImage.Name.computer) else { return }
// Set image size.
image.size = NSMakeSize(dimension / 2, dimension / 2)
// Create CGImage from NSImage
if let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) {
let imageRep = NSBitmapImageRep.init(cgImage: cgImage)
let pngData = imageRep.representation(using: .png, properties: [:])
// Set current directory as output directory
let destinationDir = URL(fileURLWithPath: "\(FileManager().currentDirectoryPath)")
// Write PNG image to disk
do {
try pngData?.write(to: destinationDir.appendingPathComponent("\(iconName).png"), options: .withoutOverwriting)
} catch {
print(error.localizedDescription)
}
}
}
generateMacIcon(dimension: 512, name: "computer")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment