0

I have two colors and I use this method to do a simple alpha blending:

int Color::blend(int col1, int col2)
{
    float a1  = ((col1 & 0x000000FF) / 255.0);
    return ((int)((((col1 & 0xFF000000) >> 24) * a1) + (((col2 & 0xFF000000) >> 24) * (1.0 - a1)))) << 24 | 
           ((int)((((col1 & 0x00FF0000) >> 16) * a1) + (((col2 & 0x00FF0000) >> 16) * (1.0 - a1)))) << 16 |
           ((int)((((col1 & 0x0000FF00) >> 8 ) * a1) + (((col2 & 0x0000FF00) >> 8 ) * (1.0 - a1)))) << 8  | 255;
}

(The colors are in RGBA8888 format)

This works, but i was wondering: is this the fastest way, or is there a more efficient one?

ScottMcGready
  • 1,612
  • 2
  • 24
  • 33
Sylar
  • 357
  • 1
  • 5
  • 15

1 Answers1

1

You might be able to eke out a little more performance by representing a1*(2^24) as an integer, doing the arithmetic in integers, then shifting the result down by 24 bits. On modern architectures I doubt it would gain you much, though. If you want better performance, you'll really need to go for SIMD operations.

Oh, one thing: You should express the calculation of a1 as a1 = ((col1 & 0x000000FF) * (1.0 / 255.0)). That'll avoid an expensive FP division. (Compilers won't usually do that on their own, due to the potential loss of precision.)

Sneftel
  • 40,271
  • 12
  • 71
  • 104