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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With