rsharma rsharma - 1 year ago 119
Objective-C Question

Creating NSImage from NSColor

I have a PopUp Button 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 of the approach, that if I can create an NSImage object using NSColor object ( which will be already present ), then I can use

-(void) setImage:(NSImage *) menuImage

method of NSMenuItem class to display the image in front of color title in the popup button.

So, How can I accomplish creating an NSImage object using NSColor?
Any other approaches to solve the problem are also welcomed. :)

Answer Source

A simple category method will do this

@interface NSImage (ImageAdditions)

+(NSImage *)swatchWithColor:(NSColor *)color size:(NSSize)size;


@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;    


[EDIT] remove deprecated API

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download