Ricardo Sanchez
Ricardo Sanchez

Reputation: 5177

Color interpolation between 3 colors

I use the following equation to get a nice color gradient from colorA to colorB, but I have no idea how to do the same for 3 colors, so the gradient goes from colorA to colorB to colorC

colorT = colorA * p + colorB * (1.0 - p); where "p" is the a percentage from 0.0 to 1.0

Thanks

Upvotes: 5

Views: 6530

Answers (5)

Raj
Raj

Reputation: 41

Thanks for the formula. But I had to make some modifications to it, as it didn't interpolate between the 3 colors properly (there was jumps in color change)

Here is the fix for that:

if (p < 0.5)
        {
            COLORx = (COLORb * p * 2.0) +  COLORa * (0.5 - p) * 2.0;
        }
        else
        {
            COLORx = COLORc * (p - 0.5) * 2.0 + COLORb * (1.0 - p) * 2.0;          
        }

Upvotes: 4

andijcr
andijcr

Reputation: 427

one possible solution is to use interpolation via Bézier Curve: http://en.wikipedia.org/wiki/B%C3%A9zier_curve if you look at the special case Quadratic Bézier Curve, you can see a formula that interpolate between 3 points, or colors in your case.

colorT=(1-p*p)Color0 + 2(1-p)Color1 + (p*p)Color2   , 0<=p<=1

This is a generalization of your linear formula.

EDIT:

on second though, this method doesn't get your results, as the intermediate point is never touched. To get a smooth curve that touch all of your points (colors) you have to use a spline http://en.wikipedia.org/wiki/Spline_interpolation

Upvotes: 1

Guffa
Guffa

Reputation: 700840

It might be possible to construct a single expression for that, but the simplest is to use a condition to use different expressions depending on whether you are in the A - B part or B - C part of the range:

colorT =
  p < 0.5
    ? colorA * p * 2.0 + colorB * (1.0 - p * 2.0)
    : colorB * (p - 0.5) * 2.0 + colorC * (1.0 - (p - 0.5) * 2.0);

Upvotes: 2

schnaader
schnaader

Reputation: 49731

Well, for 3 colors, you can just to the same with p = 0.0 to 2.0:

if p <= 1.0
  colorT = colorA * p + colorB * (1.0 - p);
else
  colorT = colorB * (p - 1.0) + colorC * (2.0 - p);

Or scale it so you can still use p = 0.0 to 1.0:

if p <= 0.5
  colorT = colorA * p * 2.0 + colorB * (0.5 - p) * 2.0;
else
  colorT = colorB * (p - 0.5) * 2.0 + colorC * (1.0 - p) * 2.0;

Upvotes: 2

daan
daan

Reputation: 254

You want to be able to create 3 color but equal gradients? Exactly the same: after you're done with this gradient, start a new one where colorA is the current colorB and colorB is the new color. Append the results and you're done:

colorA ---- colorB colorB ---- colorC

Good luck!

Upvotes: 0

Related Questions