Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created January 24, 2020 08:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/9473ea1c227dd860eae48077cf2d1d39 to your computer and use it in GitHub Desktop.
Save jmcd/9473ea1c227dd860eae48077cf2d1d39 to your computer and use it in GitHub Desktop.
Drawing to a PNG
func makePNG(_ size: NSSize, by drawing: (CGContext) -> ()) -> Data? {
guard let bitmapImageRep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSColorSpaceName.deviceRGB,
bytesPerRow: 0, bitsPerPixel: 0) else {
return nil
}
let graphicsCtx = NSGraphicsContext(bitmapImageRep: bitmapImageRep)!
let ctx = graphicsCtx.cgContext
drawing(ctx)
return bitmapImageRep.representation(using: .png, properties: [:])
}
let pngData = makePNG(rect.size) { ctx in
ctx.beginPath()
ctx.move(to: .zero)
ctx.addLine(to: NSPoint(x: 100, y: 100))
ctx.addLine(to: NSPoint(x: 100, y: 0))
ctx.addLine(to: NSPoint(x: 0, y: 100))
ctx.closePath()
ctx.strokePath()
}!
try! pngData.write(to: URL(fileURLWithPath: "/tmp/out.png"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment