Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating NSImage from NSColor

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. :)

like image 336
rsharma Avatar asked Jun 27 '12 10:06

rsharma


3 Answers

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

like image 175
Warren Burton Avatar answered Nov 24 '22 01:11

Warren Burton


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 😁

like image 21
Ky. Avatar answered Nov 24 '22 01:11

Ky.


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
  }
}
like image 22
M0rph3v5 Avatar answered Nov 24 '22 01:11

M0rph3v5