0

I have a lowest speed Color and a highest speed Color

I have another variable called currentSpeed which gives me the current speed. I'd like to generate a Color between the two extremes using the current speed. Any hints?

Grégoire Borel
  • 1,880
  • 3
  • 33
  • 55

1 Answers1

2

The easiest solution is probably to linearly interpolate each of RGB (because that is probably the format your colours are in). However it can lead to some strange results. If lowest is bright blue (0x0000FF) and highest is bright yellow (0xFFFF00), then mid way will be dark grey (0x808080).

A better solution is probably:

  • Convert both colours to HSL (Hue, saturation, lightness)
  • Linearly interpolate those components
  • Convert the result back to RGB.

See this answer for how to do the conversion to and from HSL.

To do linear interpolation you will need something like:

double low_speed = 20.0, high_speed = 40.0;  // The end points.
int low_sat = 50, high_sat = 200;            // The value at the end points.
double current_speed = 35;

const auto scale_factor = (high_sat-low_sat)/(high_speed-low_speed);
int result_sat = low_sat + scale_factor * (current_speed - low_speed);

Two problems:

  • You will need to be careful about integer rounding if speeds are not actually double.
  • When you come to interpolate hue, you need to know that they are represented as angles on a circle - so you have a choice whether to interpolate clockwise or anti-clockwise (and one of them will go through 360 back to 0).
Community
  • 1
  • 1