alpha blend图层混合算法

想象一下,多个半透明的图层叠在一起,我们从上往下能够透过半透明看到下面的多个图层的图像,并且下面图层的清晰度的随着上面图层的透明度降低而减少的。如果我们把这多个图层合并为一个图层,这个图层的图像就应该是我们从上往下看这多个图层叠在一起是一样的。

实现将带alpha通道的多个图层合并生成新的图像的原理:仅从两层来看,其关键因素在于上面图层的alpha值,下面图层的alpha值是由1-上面图层的alpha值决定的。

具体的算法如下(用这里用c语言实现):

unsigned char layerMerge(unsigned char **layers, unsigned int layerCount, unsigned int layerWidth, unsigned int layerHeight) {
	if (1 >= layerCount) return 0;
	unsigned char isNewLayer = 0;
	unsigned int i, j, byteCount;
	byteCount = layerWidth * layerHeight * 4;		/* byte count of each layer */
	unsigned char *result = layers[0];
	for (i = 1; i < layerCount; i++) {
		unsigned char *tile = layers[i];
		for (j = 0; j < byteCount;  j += 4) {
			int r = j; int g = j + 1; int b = j + 2; int a = j + 3;
			if (255 != result[a] && 0 != tile[a]) {
				isNewLayer = 1;
			}
			float alpha1 = result[a] / 255.0f;
			float alpha2 = tile[a] / 255.0f;
			float R = result[r] * alpha1 + tile[r] * alpha2 * (1 - alpha1);
			float G = result[g] * alpha1 + tile[g] * alpha2 * (1 - alpha1);
			float B = result[b] * alpha1 + tile[b] * alpha2 * (1 - alpha1);
			float A = 1 - (1 - alpha1) * (1 - alpha2);
			if (0 == result[a] && 0 == tile[a]) {
				result[r] = result[g] = result[b] = result[a] = 0;
			} else {
				result[r] = clamp((int)(R / A) + 0.5);
				result[g] = clamp((int)(G / A) + 0.5);
				result[b] = clamp((int)(B / A) + 0.5);
				result[a] = clamp((int)(A * 255) + 0.5);
			}
		}
	}
	return isNewLayer;
}

格式说明:

图片格式为rgba数组,即每个像素4个字节

图层数组顺序按从上往下排列

clamp()是确保rgba的值在0~255之间的函数:

int clamp(int val) {
  if (val < 0) return 0;
  if (val > 255) return 255;
  return val;
};

如有问题,欢迎留言批评指正!


你可能感兴趣的:(算法,alpha,blend,图层混合算法,图层合并,rgba)