Alpha融合和图片透明度[AlphaBlend]

Alpha融合,不论是在3D还是2D中都常见,最常见的应用就是:设置图片的透明度,不透明度,可以实现抠图。

 

其实现思想如下:

有个混合因子,主要是颜色混合:

  • 浮点表示:0.0f <= alpha <= 1.0f
  • 整数表示: 0x00 <= alpha <= 0xff  为了提高运算效率

分开计算R,G,B混合

/* * alpha为混合因子 0.0 <= alpha <= 1.0 * alpha为混合因子 0x00 <= alpha <= 0xff * srcColor destColor可以为Red,Green,Blue分量 */ BYTE AlphaBlend(const BYTE srcColor, const BYTE destColor, BYTE alpha = 100) { BYTE retValue= srcColor * alpha/255 + destColor * (0xff-alpha)/255; return retValue; }

 

对于32位位图,每个像素含alpha信息:

unsigned int AlphaBlend(const unsigned int bg, const unsigned int src) { unsigned int a = src >> 24; / * alpha * / / * If source pixel is transparent, just return the background * / if (0 == a) return bg; / * alpha blending the source and background colors * / unsigned int rb = (((src & 0x00ff00ff) * a) + ((bg & 0x00ff00ff) * (0xff - a))) & 0xff00ff00; unsigned int g = (((src & 0x0000ff00) * a) + ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000; return (src & 0xff000000) | ((rb | g) >> 8); }

 

我自己实现了一个简单的alpha融合,读取两张图片(bitmap),用一个设定的alpha混合因子,每个像素进行融合,然后在显示到屏幕。

目标图片:

Alpha融合和图片透明度[AlphaBlend]_第1张图片

 

背景图片:

Alpha融合和图片透明度[AlphaBlend]_第2张图片

当alpha = 100, 融合后的图片效果:

Alpha融合和图片透明度[AlphaBlend]_第3张图片

 

程序源码可以下载:

http://download.csdn.net/source/1899010

按space键增加alpha值。

当alpha = 255: 只显示目标图片。

当alpha = 0    : 只显示背景图片

 

你可能感兴趣的:(C++,算法)