Search code examples
iosuicolor

Getting a UIColor from a restricted range in the HSB spectrum


I want to use just a portion of the hue spectrum (from yellowish-green to red only) to indicate a state change specified by a calculated float value.

I found it was easy enough to use the entire spectrum:

float hue;
hue = (1.0 * [c floatValue]);

float saturation;
saturation = 1.0;

float alpha;
alpha =  1.0;

UIColor *color = [UIColor colorWithHue:hue
                            saturation:saturation
                            brightness:1.0
                                 alpha:alpha];

NSLog(@"color %@",color);


self.backgroundBar.backgroundColor = color;

But I don't want all those other colors.

c is a float value between 0.00 and 1.0

How can I restrict the sweep to the range between yellowish-green (hue = 75/255) and red (hue = 15/255)?

Thanks!


Solution

  • As you wanted to have a range between 15/255 to 75 / 255, that means if the value of c is 0 it hue will be 15/255 and if c is 1 then hue 75/255.

    Let,

    low = 15.f/255.f;
    high = 75.f/255.f;
    

    So, hue should be,

    hue = c* (high - low) + low;