Created
October 14, 2014 20:33
-
-
Save XProger/96253e93baccfbf338de to your computer and use it in GitHub Desktop.
Fast integer alpha blending
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Do we need to consider rb/g overflow?
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?
yep, check optimized version https://gist.github.com/XProger/155262f898ceb2368323
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
very nice