Created
February 9, 2025 06:56
-
-
Save SKaplanOfficial/ffedf0350bd0ba3cb4f7f6da3247c4f2 to your computer and use it in GitHub Desktop.
NSImage class extension initializer for quickly creating swatches of NSColors.
This file contains 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
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