Reputation: 1733
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];
Upvotes: 2
Views: 1285
Reputation: 7493
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
Upvotes: 1
Reputation: 125007
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.
}
Upvotes: 6
Reputation: 27506
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.
Upvotes: 1