Skip to content

Instantly share code, notes, and snippets.

@SKaplanOfficial
Created February 9, 2025 06:56
Show Gist options
  • Save SKaplanOfficial/ffedf0350bd0ba3cb4f7f6da3247c4f2 to your computer and use it in GitHub Desktop.
Save SKaplanOfficial/ffedf0350bd0ba3cb4f7f6da3247c4f2 to your computer and use it in GitHub Desktop.
NSImage class extension initializer for quickly creating swatches of NSColors.
public extension NSImage {
/// Initializes and returns a new color swatch image.
/// - Parameters:
/// - color: The fill color of the image.
/// - size: The width and height of the image.
convenience init(color: NSColor, size: NSSize) throws {
self.init(size: size)
guard let ciColor = CIColor(color: color) else {
assertionFailure("Could not create CIColor from NSColor")
return
}
let rect = CGRect(origin: .zero, size: size);
let ciImage = CIImage(color: ciColor).cropped(to: rect)
let bitmapRep = NSBitmapImageRep(ciImage: ciImage)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep)
ciImage.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
self.addRepresentation(bitmapRep)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment