Search code examples
objective-ccomponentsuicolor

get components of color in objective-c


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];

Solution

  • 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.