Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created October 27, 2014 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/3dcb2a5492a9737512d2 to your computer and use it in GitHub Desktop.
Save jmcd/3dcb2a5492a9737512d2 to your computer and use it in GitHub Desktop.
Create all the different sized iOS App Icons from a single source image
#!/usr/bin/xcrun swift
import Cocoa
import AppKit
import CoreGraphics
class Spec {
let pointSize: Int;
let scales: [Int]
init(pointSize: Int, atScale scales: [Int]){
self.pointSize = pointSize;
self.scales = scales;
}
convenience init(pointSize: Int){
self.init(pointSize: pointSize, atScale: [1, 2, 3])
}
func edgeLen(atScale scale: Int)-> Int {
return pointSize*scale
}
}
var specs = [
Spec(pointSize: 29),
Spec(pointSize: 40),
Spec(pointSize: 60),
Spec(pointSize: 76, atScale: [1,2]),
]
var inputFilePath = Process.arguments[1]
var inputImage = NSImage(byReferencingFile: inputFilePath)
var inputImageBitmapRepOrNil:NSBitmapImageRep?
for rep in inputImage?.representations as [NSImageRep] {
if let candidate = rep as? NSBitmapImageRep {
inputImageBitmapRepOrNil = candidate
}
}
if let inputImageBitmapRep = inputImageBitmapRepOrNil? {
var baseOutputFilePath = inputFilePath.stringByDeletingPathExtension
for spec in specs {
for scale in spec.scales {
var dim = spec.edgeLen(atScale: scale)
var fdim = CGFloat(dim)
var size = CGSizeMake(fdim, fdim)
var rect = CGRectMake(0.0, 0.0, fdim, fdim)
var outputBitmapRep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: dim,
pixelsHigh: dim,
bitsPerSample: inputImageBitmapRep.bitsPerSample,
samplesPerPixel: inputImageBitmapRep.samplesPerPixel,
hasAlpha: inputImageBitmapRep.alpha,
isPlanar: inputImageBitmapRep.planar,
colorSpaceName: inputImageBitmapRep.colorSpaceName,
bitmapFormat: inputImageBitmapRep.bitmapFormat,
bytesPerRow: 0,
bitsPerPixel: inputImageBitmapRep.bitsPerPixel
)
var graphicsContext = NSGraphicsContext(bitmapImageRep: outputBitmapRep!)
if let c = graphicsContext?.CGContext {
var cgImage = inputImage?.CGImageForProposedRect(nil, context: graphicsContext, hints: nil)?.takeUnretainedValue()
CGContextDrawImage(c, rect, cgImage)
var data = outputBitmapRep!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties:[:])
var outputFilePath = "\(baseOutputFilePath)\(spec.pointSize)pt@\(scale)x.png"
data!.writeToFile(outputFilePath, atomically:false)
}
}
}
}
@jmcd
Copy link
Author

jmcd commented Oct 27, 2014

Run

mkappicons.swift MyAppIcon.png 

To get

MyAppIcon29pt@1x.png
MyAppIcon29pt@2x.png
MyAppIcon29pt@3x.png
MyAppIcon40pt@1x.png
MyAppIcon40pt@2x.png
MyAppIcon40pt@3x.png
MyAppIcon60pt@1x.png
MyAppIcon60pt@2x.png
MyAppIcon60pt@3x.png
MyAppIcon76pt@1x.png
MyAppIcon76pt@2x.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment