透明颜色混合算法

一般数学计算中,颜色取值是: R , G , B ∈ [ 0 , 255 ] , A ∈ [ 0 , 1 ] R,G,B \in \left [ 0, 255 \right ], A\in \left [ 0, 1 \right ] R,G,B[0,255],A[0,1]
所以对于一般的颜色混合有: C o l o r ( R G B A ) = C o l o r ( R 1 G 1 B 1 A 1 ) + C o l o r ( R 2 G 2 B 2 A 2 ) Color(RGBA) = Color(R_{1}G_{1}B_{1}A_{1}) + Color(R_{2}G_{2}B_{2}A_{2}) Color(RGBA)=Color(R1G1B1A1)+Color(R2G2B2A2)

标准的颜色混合算法如下:
A = 1 − ( 1 − α 1 ) ∗ ( 1 − α 2 ) A = 1 - \left ( 1-\alpha _{1} \right )*\left ( 1-\alpha _{2} \right) A=1(1α1)(1α2)
R = 1 A ( α 1 R 1 + ( 1 − α 1 ) α 2 R 2 ) R = \frac{1}{A}(\alpha _{1}R_{1}+ (1 - \alpha _{1})\alpha _{2}R_{2}) R=A1(α1R1+(1α1)α2R2)
G = 1 A ( α 1 G 1 + ( 1 − α 1 ) α 2 G 2 ) G = \frac{1}{A}(\alpha _{1}G_{1}+ (1 - \alpha _{1})\alpha _{2}G_{2}) G=A1(α1G1+(1α1)α2G2)
B = 1 A ( α 1 B 1 + ( 1 − α 1 ) α 2 B 2 ) B = \frac{1}{A}(\alpha _{1}B_{1}+ (1 - \alpha _{1})\alpha _{2}B_{2}) B=A1(α1B1+(1α1)α2B2)

但是在计算机图像中,透明度alpha通常也是 A ∈ [ 0 , 255 ] A \in \left [ 0, 255 \right ] A[0,255]
所以,根据变化得到的代码是:

//浮点数版
float a1 = A1 / 256.0;
float a2 = A2 / 256.0;
float a = 1 - (1 - a1)*(1 - a2);

R = (a1*R1 + (1 - a1)*a2*R2) / a;
G = (a1*G1 + (1 - a1)*a2*G2) / a;
B = (a1*B1 + (1 - a1)*a2*B2) / a;
A = a * 256;

化简后:

float a1 = A1;
float a2 = A2 - (a1 * A2)/256;
float a = a1 + a2;

R = (a1*R1 + a2*R2)/a;
G = (a1*G1 + a2*G2)/a;
B = (a1*B1 + a2*B2)/a;
A = a;

你可能感兴趣的:(C/C++)