Skip to content

Instantly share code, notes, and snippets.

@petebarber
Last active August 29, 2015 14:20
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 petebarber/59b6a76c84713f19b799 to your computer and use it in GitHub Desktop.
Save petebarber/59b6a76c84713f19b799 to your computer and use it in GitHub Desktop.
OSX/Cocoa command line program to create a bitmap, draw into it and save as a PNG. In this case it draws triangles that are used a basic grass asset
import Cocoa
private func saveAsPNGWithName(fileName: String, bitMap: NSBitmapImageRep) -> Bool
{
let props: [NSObject:AnyObject] = [:]
let imageData = bitMap.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: props)
return imageData!.writeToFile(fileName, atomically: false)
}
private func drawGrassIntoBitmap(bitmap: NSBitmapImageRep)
{
var ctx = NSGraphicsContext(bitmapImageRep: bitmap)
NSGraphicsContext.setCurrentContext(ctx)
NSColor(red: 124 / 255, green: 252 / 255, blue: 0, alpha: 1.0).set()
let path = NSBezierPath()
path.moveToPoint(NSPoint(x: 0, y: 0))
for i in stride(from: 0, through: SIZE.width, by: 40)
{
path.lineToPoint(NSPoint(x: CGFloat(i + 20), y: CGFloat(arc4random_uniform(400))))
path.lineToPoint(NSPoint(x: i + 40, y: 0))
}
path.stroke()
path.fill()
}
let SIZE = CGSize(width: 800, height: 400)
if Process.arguments.count != 2
{
println("usage: grass <file>")
exit(1)
}
let grass = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(SIZE.width), pixelsHigh: Int(SIZE.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)
drawGrassIntoBitmap(grass!)
saveAsPNGWithName(Process.arguments[1], grass!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment