Extracting rgb from UIColor

J T picture J T · May 3, 2009 · Viewed 58.8k times · Source

Seen this asked before but my example does not seem to work.

const CGFloat *toCol = CGColorGetComponents([[UIColor greenColor] CGColor]);

The array is empty from looking at it with GDB. Any hints?

Answer

Pablo Santa Cruz picture Pablo Santa Cruz · May 3, 2009

The code sample you provided should work.

Try this:

UIColor uicolor = [[UIColor greenColor] retain];
CGColorRef color = [uicolor CGColor];

int numComponents = CGColorGetNumberOfComponents(color);

if (numComponents == 4)
{
  const CGFloat *components = CGColorGetComponents(color);
  CGFloat red = components[0];
  CGFloat green = components[1];
  CGFloat blue = components[2];
  CGFloat alpha = components[3];
}

[uicolor release];