rsharma rsharma - 10 days ago 6
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

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

Comments