What is the most effective way to interpolate between two colors? (Pseudocode and expected bitwise operations)

advertisements

Making a Blackberry app, want a Gradient class. What's the most effective way (as in, speed and battery life) to interpolate two colors? Please be specific.

// Java, of course
int c1 = 0xFFAA0055   // color 1, ARGB
int c2 = 0xFF00CCFF   // color 2, ARGB
float st = 0          // the current step in the interpolation, between 0 and 1

Help from here on. Should I separate each channel of each color, convert them to decimal and interpolate? Is there a simpler way?

interpolatedChannel = red1+((red2-red1)*st)
interpolatedChannel = interpolatedChannel.toString(16)

^ Is this the right thing to do? If speed and effectiveness is important in a mobile app, should I use bitwise operations?

Help me!


You'll have to separate channels, but there's no need to convert them to decimal.

For example, if you allow 256 possible gradients:

red = red1 + ((red2 - red1) * stage / 256)

EDIT: Since you said you don't know much about bit management, here's a quick way to split channels:

red = color & 0x000000ff;
green = color & 0x0000ff00;
blue = color & 0x00ff0000;
alpha = color >> 24;

And combining them back:

color = (alpha << 24) | blue | green | red;

From here, the details should normally be handled by the compiler optimizations. If anything, you're looking for the best algorithm.