Skip to content

Instantly share code, notes, and snippets.

@skagedal
Last active June 9, 2018 18:04
Show Gist options
  • Save skagedal/979ae0ab8ce33d0005c79dd42569e86c to your computer and use it in GitHub Desktop.
Save skagedal/979ae0ab8ce33d0005c79dd42569e86c to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
enum ImageError: Error {
case couldNotCreateBitmapImage
case couldNotCreatePNGRepresentation
}
func renderIcon(text: String, backgroundColor: NSColor, sizeInPixels: Int) throws -> Data {
guard let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: sizeInPixels, pixelsHigh: sizeInPixels, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) else {
throw ImageError.couldNotCreateBitmapImage
}
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: imageRep)
let string = text as NSString
let width = CGFloat(sizeInPixels)
let imageSize = NSSize(width: width, height: width)
let font = NSFont.systemFont(ofSize: width * 0.843)
let attributes: [NSAttributedString.Key : Any] = [.font: font]
let rect = string.boundingRect(with: imageSize, options: [], attributes: attributes)
NSColor.white.setFill()
NSRect(x: 0, y: 0, width: width, height: width).fill()
string.draw(in: NSRect(x: width / 2 - rect.width / 2,
y: width / 2 - rect.size.height / 2 ,
width: rect.width,
height: rect.height),
withAttributes: attributes)
guard let data = imageRep.representation(using: .png, properties: [:]) else {
throw ImageError.couldNotCreatePNGRepresentation
}
return data
}
let imageData = try renderIcon(text: "🍓", backgroundColor: .white, sizeInPixels: 100)
let url = URL(fileURLWithPath: "/Users/simon/Desktop/Icon100.png")
try imageData.write(to: url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment