2

Here is a code snippets for get RGB components of color. What can I do if the _countComponents is less than four, for example two? I tried to get components of color gray [UIColor grayColor]

int _countComponents = CGColorGetNumberOfComponents(colorRef);

if (_countComponents == 4) {
    const CGFloat *_components = CGColorGetComponents(colorRef);
    CGFloat red     = _components[0];
    CGFloat green = _components[1];
    CGFloat blue   = _components[2];
    CGFloat alpha = _components[3];
L. Kvri
  • 1,456
  • 4
  • 23
  • 41
  • What do you mean by: *" I tried to get components of color gray [UIColor grayColor]"*? – sch Feb 21 '12 at 19:42

3 Answers3

6

If you've got an instance of UIColor and you want it's RGB values, why not use the -getRed:green:blue:alpha: method?

CGFloat r, g, b, a;
BOOL success = [myColor getRed:&r green:&g blue:&b alpha:&a];
if (success) {
    // the color was converted to RGB successfully, go ahead and use r,g,b, and a.
}
sch
  • 27,436
  • 3
  • 68
  • 83
Caleb
  • 124,013
  • 19
  • 183
  • 272
1

The components of a color depend on the associated color space.

So _components[0], _components[1], etc are not necessary red, green blue and alpha.

sch
  • 27,436
  • 3
  • 68
  • 83
1

New Answer

After re-reading the question. To answer the Gray components question, the way you read that is via -(BOOL)getWhite:alpha:

So you would do as per Caleb with something like:

BOOL success = [myColor getWhite:&w alpha:&a];

This gives you the gray value w as 0 to 1 and the alpha value a as 0 to 1

See the Apple docs getWhite:alpha:

Old answer

From this SO question how-to-access-the-color-components-of-an-uicolor

See the (rather old) ArsTechnica artical iphone-development-accessing-uicolor-components

Community
  • 1
  • 1
Peter M
  • 7,309
  • 3
  • 50
  • 91