I am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition.
For testing purposes, I will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans.
Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to.Net (VB/C#).
Currently I have:
t = 300
x = t/2
z = 0
low = Green (0, 255, 0)
mid = Yellow (255, 255, 0)
high = Red (255, 0, 0)
Lastly, sort of an optional piece, is to account for the possibility of the low
, mid
, and high
color’s to be flexible as well. I assume that there would need to be a check to make sure that someone isn’t putting in low = (255,0,0)
, mid=(254,0,0)
, and high=(253,0,0)
. Outside of this anomaly, which I will handle myself based on the best approach to evaluate a color.
Question:
- What would be the best approach to do the transition from
low
tomid
and then frommid
tohigh
? - What would be some potential pitfalls of implementing this type of design, if any?
You can’t really do it smoothly using the RGB color space, but it’s easier when done with HSV.
See HSL and HSV
Using HSV space you can transition from Green to Yellow to Red along a single float value for Hue while keeping the saturation/value constant.
5
While you can do the transition in RGB space (using component-wise linear interpolation), this might cause unnaturally-looking transitions; most noticably, the brightness and saturation may bump between control points. If it this is acceptable, just do it this way. Mapping the values through some sort of gamma function before interpolating and then reverting the gamma on the interpolated values may alleviate the bumps a bit.
If that’s not good enough, convert your colors into a color space closer to how the human perception works, such as HSI (hue – saturation – intensity). Then apply the same interpolation, but do keep in mind that the hue component is circular, that is, if you have hues ranging from 0 to 100, and your input colors are at 95 and 5, you want to move forward and then wrap around (thus 95 up to 100 and then “jump” to 0, continuing up to 5) instead of going down from 95 to 5 – think of the hue axis as a circle along which you travel; your interpolation should take the shorter route along the circle’s edge.
The HSI calculation is more expensive, because you have to convert the interpolated HSI value back to RGB for display on each frame, but it yields much better results, because the hue, brightness and saturation transition independently without causing perceived artifacts.
1