PrEV
Thoughts from a NeXTStep Guy on Cocoa Development

NSColor & CGColorRef

Sep 06, 2008 by Bill Dudney

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.

Permalink     Add A Comment