NSColor & CGColorRef
While writing an example of how to understand the 3D transforms possible with CALayer I had a bit of an epiphany about how to make building colors easier. Instead of the utility class I'd been using I cooked up this little category on NSColor. Of course I should have thought of this first but my brain has been weakened by years of Java coding...
@implementation NSColor(CGColor)
- (CGColorRef)CGColor {
CGColorSpaceRef colorSpace = [[self colorSpace] CGColorSpace];
NSInteger componentCount = [self numberOfComponents];
CGFloat *components = (CGFloat *)calloc(componentCount, sizeof(CGFloat));
[self getComponents:components];
CGColorRef color = CGColorCreate(colorSpace, components);
free((void*)components);
return color;
}
@end
This has the disadvantage of creating a new instance on each call. If you (or I) wanted to get really fancy you could look to see if the NSColor is a named instance and if so place the CGColorRef into a CFDictionary and thus cache the CGColorRef's but I think I'll leave that to my next Epiphany.
Code is licensed under Apache 2.0, do with it what you will.




You should probably do a little bit of exception handling when converting colours like this - it's possible the user will select a pattern rather than a straight NSColor: http://tonyarnold.com/code-snippets/nscolor-cgcolorref/
Posted by Tony Arnold on April 03, 2009 at 02:05 AM MDT #