Matt Legend Gemmell Modesty is Lying

Mac OS X Cocoa and iPhone Development Services available at Instinctive Code.
Mac OS X Cocoa and iPhone Developer for hire

Other Pages

Categories

Posted
16 August 2006 @ 9pm

Categories
Development, Source

Tags
, , , , , ,

NSColor+ContrastingLabelExtensions

A quick Cocoa source code post. This one is simple: it’s a category on NSColor which returns another NSColor for use when drawing label text on top of the receiver. Either white or black is returned, depending on which will have most visual contrast with the receiver’s color. In the event of the receiver’s colorspace not being converted to RGB, black is returned by default.

Download the source code (includes a sample app, as always). This code came about due to a conversation I was having today with Iain, so cheers to the man himself for that.


3 Comments

Alberto Ricart
22 August 2006 @ 12am

Matt,

The exact ‘gray’ value of an RGB color can be determined more precisely as:

(0.3*red)+(0.59*green)+(0.11*blue)

This takes into account perceptual issues like the green component contributes more to the luminosity of the color than the red, and the red more than the blue.

Neat sample all the same.

Cheers,

/a


Matt Gemmell
22 August 2006 @ 12pm

Nice tip there Alberto, cheers for that. :)


Ulfrinn
12 February 2008 @ 5pm

Did not work for me with +[NSColor blackColor] on Leopard (haven’t tried on earlier systems, though). I had to change the color space conversion as detailed at http://www.zathras.de/angelweb/blog-cocoa-in-supercompiler.htm, so that line 16 would read:
NSColor *rgbColor = [self colorUsingColorSpaceName:NSDeviceRGBColorSpace];
Works perfectly now—thanks for this handy category, Matt!


Leave a Comment

Moving to Edinburgh I’m off