Search code examples
c++openframeworks

Interpolate from one color to another


I am trying to get an interpolation of one color to another shade of the same color. (for eg: sky blue to dark blue and then back).

I stumbled upon some code that could be used if the range was from 0-255 or 0-1. However, in my case, I have the RGB codes for Color1 and Color2, and want the rotation to occur.

Color 1: 151,206,255
Color 2: 114,127,157

Any ideas how to go about this?


Solution

  • I suggest you convert RGB to HSV, then adjust its components, then convert back to RGB.

    Wikipedia has an article about it, and it's been discussed here before:

    HSL to RGB color conversion

    Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

    Also many frameworks have conversion functions, for example Qt has QColor class.


    But the question was about the actual interpolation... here's a trivial interpolation function:

    // 0 <= stepNumber <= lastStepNumber
    int interpolate(int startValue, int endValue, int stepNumber, int lastStepNumber)
    {
        return (endValue - startValue) * stepNumber / lastStepNumber + startValue;
    }
    

    So call that for all color components you want to interpolate, in a loop. With RBG interpolation, you need to interpolate every component, in some other color space you may need to interpolate just one.