Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting HSB color to RGB in Objective C

I'm trying to convert HSB values to RGB values using this algorithm, but I am not getting correct values. I have a fixed s of 29, a fixed b of 100, and am generating random integers between 0-360 for the h value, and feeding them into the function to get RGB back:

enter image description here

float h = (arc4random() % 360);
float s = 29;
float b = 100;
HSL2RGB(h, s, b, &red, &green, &blue);
NSLog(@"r:%f g:%f b:%f", red, green, blue);

output:

r:2971.000000 g:2971.000000 b:2971.000000

I tried this too:

float h = (arc4random() % 360)/1000.0;
float s = 0.29;
float b = 1.0;
HSL2RGB(h, s, b, &red, &green, &blue);
NSLog(@"r:%f g:%f b:%f", red, green, blue);

output:

r:1.000000 g:1.000000 b:1.000000

Am I doing something wrong, or is this algorithm messed up?

like image 560
Snowman Avatar asked Dec 07 '22 13:12

Snowman


1 Answers

You can get the RGB components of a color constructed using HSB directly and easily using UIKit.

UIColor *color = [UIColor colorWithHue: hue saturation: saturation
                            brightness: brightness alpha: alpha];
if ( [color getRed: &red green: &green blue: &blue alpha: &alpha] ) {
    // color converted
}

If all you care about is using the color, you can skip the if and just use it.

Per Apple's UIColor documentation:

If the color is in a compatible color space, the color is converted into RGB format and its components are returned to your application. If the color is not in a compatible color space, the parameters are unchanged.

A compatible color space in this case is RGB or HSB.

like image 200
Steven Fisher Avatar answered Dec 27 '22 19:12

Steven Fisher