Color . Lerp

Color . Lerp

This post discusses about the tricky problem of colour interpolation, and explores possible solutions. Many software and engines offer read-to-use functions to interpolate colours. In Unity, for instance,is available and does its job pretty nicely. Use the interactive swatch below to see howworks.

There’s nothing wrong in using these functions, as long as you know what the deal with colour interpolation is.

Understanding interpolation

Interpolation is a technique that allows you to “fill a gap” between two numbers. Most APIs expose linear interpolation based on three parameters: the starting point , the ending point and a value between 0 and 1 which moves along the segment that connected them:

When , is returned. When , is returned instead. The beauty of this formula is that is easy to understand, efficient to implement, and it works in any dimension. Lerping in two dimension only requires to independently lerp the X and Y components. Lerping always returns points on the line that connects and , regardless of the number of dimensions. A standard RGB lerp can be done as such:

public static Color LerpRGB (Color a, Color b, float t) { return new Color ( a.r + (b.r - a.r) * t, a.g + (b.g - a.g) * t, a.b + (b.b - a.b) * t, a.a + (b.a - a.a) * t ); } 1 2 3 4 5 6 7 8 9 10 public static Color LerpRGB ( Color a , Color b , float t ) { return new Color ( a . r + ( b . r - a . r ) * t , a . g + ( b . g - a . g ) * t , a . b + ( b . b - a . b ) * t , a . a + ( b . a - a . a ) * t ) ; }

x

If it’s true that linear interpolation works as expected in three dimensions, the same cannot say for colours. There’s a fundamental difference between the XYZ and RGB spaces: the way the human eye perceive colours. While it make sense to connect two points in a 3D space with a line, the same doesn’t always apply for points in the RGB space. Interpolating the R, G and B components independently offers no guarantee on the hue of the intermediate colours. As Stuart Denman highlights in his Improve Color Blending, the RGB space of cyan and red meet halway in grey. A new hue appears because the RGB space does not capture how Humans perceive colours very well.

The next pages of this post will explore better ways to interpolate colours.