views:

43

answers:

3

I'm wrestling with how to interpolate a color, given a start_time and end_time, start_color and end_color. For simplicity, here is an example of how I'm thinking of doing it with just the red component:

start_time = 0
end_time = 1
start_color = F //base 16 ftw
end_color = 0

I can see how at time .5, red_out should be 8. This would be midway through fading from bright red to black.

So is it time_elapsed * start_color? But then what if it's fading the other way, from black to bright red? This is where I get confused.

+1  A: 

for each color component you have to use the following formula (nothing magical):

color = time_elapsed * (end_color - start_color) / (end_time - star_time)
gustavogb
+1  A: 

The other way seems simple enough, if you think that at time t (where t ranges from 0 to 1), the value of the channel is:

start + t * (end - start)

This way, if the end value is less than the start value (as in the red -> black case), the end - start clause is negative, so as time increases the value decreases as needed.

It's also to see that in the edge cases,

t = 0   =>   start + 0 = start
t = 1   =>   start + (end - start) = end

as required.

Edit: The nice thing about this representation is that it makes it clear how to modify the rate of decay as well. So long as the value for t starts off at 0 and eventually hits 1, it doesn't necessarily have to be modified linearly. For instance, if you wanted the interpolation to start slowly and accelerate towards the end you could use t2 instead.

Andrzej Doyle
+1  A: 
interpolated_color_component = (current_time - start_time) / (end_time - start_time) * (end_color_component - start_color_component) + start_color_component
John Lemberger