Search code examples
cocoamacos-carboncore-foundation

NSColor Core Foundation counterpart?


Is there a “toll-free bridged” Core Foundation counterpart for NSColor?

CGColorRef doesn't seem to like NSColor and vice versa?

Basically we'd like to create NSColor (or compatible) objects from our C++ wrapper/framework classes that store the actual r/g/b/a values. I know we could use Objective-C++ but staying in the C++ world would be preferrable!

Any hints much appreciated.


Solution

  • You could convert a CGColorRef to an NSColor like this:

    CGColorRef cgColor = ...;
    NSColorSpace *colorSpace = [[[NSColorSpace alloc] initWithCGColorSpace:CGColorGetColorSpace(cgColor)] autorelease];
    NSColor *nsColor = [NSColor colorWithColorSpace:colorSpace 
                                         components:CGColorGetComponents(cgColor) 
                                              count:CGColorGetNumberOfComponents(cgColor)];
    

    If you use this a lot, it's probably best to put this in an NSColor category method.

    If your colors are all in the RGBA colorspace, it might be easier to just use a simple struct in your C++ code and use colorWithCalibratedRed:green:blue:alpha: for conversion.