2

There's this method in UIColor in iOS 5:

- (BOOL)getHue:(CGFloat *)hue saturation:(CGFloat *)saturation brightness:(CGFloat *)brightness alpha:(CGFloat *)alpha

But i don't understand how i'm meant to use that in code. Surely i don't need to be stating each of those components if i'm looking to get that out of the UIColor?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Andrew
  • 15,935
  • 28
  • 121
  • 203
  • 2
    Please make it a point to study this when posting on the site http://stackoverflow.com/editing-help Don't make us clean up your code every single time. – BoltClock Nov 25 '11 at 06:01

2 Answers2

16
CGFloat hue;
CGFloat saturation;
CGFloat brightness;
CGFloat alpha;

[aColor getHue:&hue 
    saturation:&saturation 
    brightness:&brightness 
         alpha:&alpha];    
//now the variables hold the values

getHue:saturation:brightness:alpha: returns a bool, determining, if the UIColor could had been converted at all.

Example:

BOOL b = [[UIColor colorWithRed:.23 green:.42 blue:.9 alpha:1.0] getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
NSLog(@"%f %f %f %f %d", hue, saturation, brightness, alpha, b);

will log 0.619403 0.744444 0.900000 1.000000 1, as it is valid

while

BOOL b = [[UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern.png"]] getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
NSLog(@"%f %f %f %f %d", hue, saturation, brightness, alpha, b);

logs 0.000000 0.000000 -1.998918 0.000000 0. The last 0 is the Bool, so this is not valid, and actually brightness can only range from 0.0 to 1.0, but here it holds some random crap.

Conclusion

The code should be something like

CGFloat hue;
CGFloat saturation;
CGFloat brightness;
CGFloat alpha;

if([aColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]){
    //do what ever you want to do if values are valid
} else {
    //what needs to be done, if converting failed? 
    //Some default values? raising an exception? return?
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
8

Notice that those four parameters are pointers to CGFloats, not just values. This is standard C pass-by-reference. See also the following Stack Overflow questions:

As an example:

CGFloat hue, saturation, brightness, alpha;
[myColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
// hue, saturation, brightness, and alpha are now set
Community
  • 1
  • 1
Jim Puls
  • 79,175
  • 10
  • 73
  • 78