Skip to content

Instantly share code, notes, and snippets.

@XProger
Created October 14, 2014 20:33
Show Gist options
  • Save XProger/96253e93baccfbf338de to your computer and use it in GitHub Desktop.
Save XProger/96253e93baccfbf338de to your computer and use it in GitHub Desktop.
Fast integer alpha blending
uint32 blend(uint32 color1, uint32 color2, uint8 alpha) {
uint32 rb = color1 & 0xff00ff;
uint32 g = color1 & 0x00ff00;
rb += ((color2 & 0xff00ff) - rb) * alpha >> 8;
g += ((color2 & 0x00ff00) - g) * alpha >> 8;
return (rb & 0xff00ff) | (g & 0xff00);
}
@glouw
Copy link

glouw commented Apr 29, 2019

very nice

@lili2012
Copy link

lili2012 commented Jun 11, 2020

Do we need to consider rb/g overflow?

@lili2012
Copy link

lili2012 commented Jun 11, 2020

I test it:

for (int64_t dst = 0; dst <= 255; dst++) {
   for (int64_t src = 0; src <= 255; src++) {
     for (int64_t Ea = 0; Ea <= 255; Ea++) {
       int64_t result = dst + (src - dst) * Ea / 255;
       if (result > 255 || result < 0) {
         printf("[dst]:[%lld] \t[src]:[%lld]\t[Ea]:[%lld]\n", dst, src, Ea);
       }
     }
   }
 }

and printf never be executed. Indicate no overflow. If so could return (rb & 0xff00ff) | (g & 0xff00); change to return rb | g?

@XProger
Copy link
Author

XProger commented Jun 11, 2020

@lili2012
Copy link

lili2012 commented Jun 11, 2020

Since you are dividing 256 not 255 so in your case return (rb & 0xff00ff) | (g & 0xff00); cant change to return rb | g;
Anyway, I like this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment