Created
August 29, 2022 19:54
-
-
Save GeekAndDad/6059e86b492e941ff2b613d45d2fc9df to your computer and use it in GitHub Desktop.
Sample of drawing into a bitmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Author
GeekAndDad
commented
Aug 29, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment