Creating NSImage from NSColor
A simple category method will do this
@interface NSImage (ImageAdditions)
+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size;
@end
@implementation NSImage (ImageAdditions)
+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size
{
NSImage *image = [[[NSImage alloc] initWithSize:size] autorelease];
[image lockFocus];
[color drawSwatchInRect:NSMakeRect(0, 0, size.width, size.height)];
[image unlockFocus];
return image;
}
@end
[EDIT] remove deprecated API
If you're using AppKit, here's a Swift 5 convenience initializer version of the other answers. Sadly, this doesn't work in UIKit ð
extension NSImage {
convenience init(color: NSColor, size: NSSize) {
self.init(size: size)
lockFocus()
color.drawSwatch(in: NSRect(origin: .zero, size: size))
unlockFocus()
}
}
Usage example:
let redSwatchImage = NSImage(color: .red, size: NSSize(width: 128, height: 128))
Feel free to change the semantics as necessary ð