Objective-c – Creating NSImage from NSColor

cocoaobjective c

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. 🙂

Best Answer

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

Related Topic