Skip to content

Instantly share code, notes, and snippets.

@GeekAndDad
Created August 29, 2022 19:54
Show Gist options
  • Save GeekAndDad/6059e86b492e941ff2b613d45d2fc9df to your computer and use it in GitHub Desktop.
Save GeekAndDad/6059e86b492e941ff2b613d45d2fc9df to your computer and use it in GitHub Desktop.
Sample of drawing into a bitmap
import Cocoa
print( NSImageRep.registeredClasses ) // -> [NSPDFImageRep, NSPICTImageRep, NSEPSImageRep, NSBitmapImageRep]
func test() {
guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: 256,
pixelsHigh: 256,
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .deviceRGB,
bitmapFormat: .alphaFirst,
bytesPerRow: 0, // auto
bitsPerPixel: 32) else {
print("Failed to make graphics context")
return
}
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
// Draw content...
let r = NSRect(x: 10.0, y: 10.0, width: 30.0, height: 30.0)
let path = NSBezierPath(rect: r)
NSColor.red.set()
path.fill()
NSGraphicsContext.restoreGraphicsState()
guard let data = rep.representation(using: .png, properties: [:]) else {
print("Failed to make png data representation")
return
}
var url = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/examplepng.png", isDirectory: false)
.standardizedFileURL
.path
print(url)
if !FileManager.default.createFile(atPath: url,
contents: data,
attributes: [:]) {
print("create file failed")
} else {
print("PNG created at: \(url)")
}
}
test()
@GeekAndDad
Copy link
Author

examplepng

@GeekAndDad
Copy link
Author

Screen Shot 2022-08-29 at 1 10 56 PM

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