I have a NSPopUpButton
which contains a list of colors. In front of the color title, I need to display a small box of the same color (maybe an image of same color). So, I was thinking that if I can create an NSImage
using NSColor
(which will be already present), then I can use the -[NSMenuItem setImage:]
method to display the image in front of the color title in the popup button.
So, how can I create an NSImage
using NSColor
?
Any other approaches to solve the problem are also welcome. :)
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 😁
And the swift extension variant of above:
import Cocoa
extension NSImage {
class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
let image = NSImage(size: size)
image.lockFocus()
color.drawSwatchInRect(NSRect(origin: .zero, size: size))
image.unlockFocus()
return image
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With