Alpha Blending 2 RGBA colors in C [duplicate]

主宰稳场 提交于 2019-12-03 17:45:58

问题


Possible Duplicate:
How to do alpha blend fast?

What is the fastest way to alpha blend 2 RGBA (Integer) colors?

As a note, the target color where to blend is always opaque, only the second color can have different levels of transparency.

I am trying to find the fastest way in C, taking into account that the final resulting color from the blend must end up with no transparency, fully opaque (alpha = 0xff)


回答1:


int blend(unsigned char result[4], unsigned char fg[4], unsigned char bg[4])
{
    unsigned int alpha = fg[3] + 1;
    unsigned int inv_alpha = 256 - fg[3];
    result[0] = (unsigned char)((alpha * fg[0] + inv_alpha * bg[0]) >> 8);
    result[1] = (unsigned char)((alpha * fg[1] + inv_alpha * bg[1]) >> 8);
    result[2] = (unsigned char)((alpha * fg[2] + inv_alpha * bg[2]) >> 8);
    result[3] = 0xff;
}

I don't know how fast it is, but it's all integer. It works by turning alpha (and inv_alpha) into 8.8 fixed-point representations. Don't worry about the fact that alpha's min value is 1. In that case, fg[3] was 0, meaning the foreground is transparent. The blends will be 1*fg + 256*bg, which means that all the bits of fg will be shifted out of the result.

You could do it very fast, indeed, if you packed your RGBAs in 64 bit integers. You could then compute all three result colors in parallel with a single expression.



来源:https://stackoverflow.com/questions/12011081/alpha-blending-2-rgba-colors-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!