views:

1529

answers:

1

Is there a Cocoa Touch way to convert colors from one color space to another?

At the end of this code:

UIColor *grey = [UIColor colorWithWhite: 0.5 alpha: 1.0];
CGColorRef greyRef = [grey CGColor];
int x = CGColorGetNumberOfComponents(greyRef);

...x is 2.

The reason I need this is I'm trying to copy colors to a list of color components for CGGradientCreateWithColorComponents, which needs all colors in a single colorspace. The problem is that grey is in the grayscale colorspace, rather than the RGB one. (The name escapes me at the moment, but it isn't important.)

CGGradientRef createGradient(NSInteger inCount, NSArray* inColors, CGFloat* inLocations) {
 CGColorSpaceRef theColorspace = CGColorSpaceCreateDeviceRGB( );
 size_t numberOfComponents = 4;
 NSInteger colorSize = numberOfComponents * sizeof( CGFloat );
 CGFloat *theComponents = malloc( inCount * colorSize );
 CGFloat *temp = theComponents;
 for ( NSInteger i = 0; i < inCount; i++ ) {
  UIColor *theColor = [inColors objectAtIndex: i];
  CGColorRef cgColor = [theColor CGColor];
  const CGFloat *components = CGColorGetComponents( cgColor );
  memmove( temp, components, colorSize );
  temp += numberOfComponents;
 }
 CGGradientRef gradient = CGGradientCreateWithColorComponents( theColorspace,
                                               theComponents, inLocations, inCount );
 CGColorSpaceRelease( theColorspace );
 free( theComponents );
 return gradient;
}

I know I can look for colors in the greyscale color space and convert them. But that only solves one case. From looking at this question, I think HSB is handled as well. But I'd like to write some code here and never think about it again, which means supporting not just the color spaces that are there now but anything Apple could conceivably add in the future. Am I out of luck?

+1  A: 

You may want to take a look at the following URLs:

http://ofcodeandmen.poltras.com/2009/01/22/convert-a-cgcolorref-to-another-cgcolorspaceref/

http://paste.lisp.org/display/74983

http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars

The first two use undocumented, private APIs, so beware. Take a look at the last one and verify if the source code available fulfills your needs.

unforgiven
Thanks. I don't think I want to touch the private APIs, so I'll use the somewhat uglier method and file a bug report against Apple to make a public one.
Steven Fisher