2012-02-14

It is funny that there are three similar but different color systems in OS X. Cocoa provides NSColor and NSColorSpace which play well with the AppKit and Foundation frameworks. Quartz provides CGColor and CGColorSpace which play well with Core Foundation and Core Animation. Core Image provides its own CIColor class which uses Quartz's CGColorSpace. There are several convenience methods for moving around this triangle of formats, but some parts are missing.

CIColor, AppKit additions: - (id)initWithColor:(NSColor *)color;

CIColor: + (CIColor *)colorWithCGColor:(CGColorRef)c;

CIColor: - (id)initWithCGColor:(CGColorRef)c;

NSColor: + (NSColor *)colorWithCIColor:(CIColor *)color;

missing: CIColor to CGColor

missing: NSColor to CGColor

missing: CGColor to NSColor

The missing methods would be nice to have when working with CGColors in Core Animation but storing NSColor values in an NSDictionary. The NSColor+ColorSystemConversions category below provides the missing conversion from CIColor to CGColor and implements the remaining side of the triangle by converting the other formats through CIColor. The #if 0 blocks show how to do the conversion directly by extracting the component arrays of the source color.

For some applications, you may not need to convert the colors at all. You could save a CGColorRef in an NSMutableDictionary by wrapping it in an NSValue. Then you would have to remember to insert CGColorRetain() and CGColorRelease() calls at the appropriate points.