Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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")
// Make sure our minimum rendering size is greater than 0
guard dimension > 0 else {
print("Error: Please provide a non-negative dimension value")
// Try to create an NSImage of the computer model if not bail out
guard let image = NSImage(named: 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 {
generateMacIcon(dimension: 512, name: "computer")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.