用Java实现颜色透明值混算的一种方法

类别:Java 点击:0 评论:0 推荐:

主页:http://www.maxss.net
Email: [email protected]

  在进行多媒体或游戏程序开发时,会需要对重叠的颜色处理其透明度以产生更好的效果。下面为大家介绍如何用Java语言实现透明值混算的方法。

  各点像素的RGB值是按一定比例混合而成的,这个比例由Alpha值决定,具体算式见下:

  Alpha = 0 ~ 100
  R = ( R1 * (100 - Alpha) + R2 * Alpha ) / 100
  G = ( G1 * (100 - Alpha) + G2 * Alpha ) / 100
  B = ( B1 * (100 - Alpha) + B2 * Alpha ) / 100

  示例:
  RGB1 ( 232, 54, 13 )
  RGB2 ( 94, 186, 233 )

  Alpha = 30
  R = ( 232 * 70 + 94 * 30 ) / 100 = 190.6 -> 190
  G = ( 54 * 70 + 186 * 30 ) / 100 = 93.6 -> 93
  B = ( 13 * 70 + 233 * 30 ) / 100 = 79
  Alpha = 50
  R = ( 232 * 50 + 94 * 50 ) / 100 = 163
  G = ( 54 * 50 + 186 * 50 ) / 100 = 120
  B = ( 13 * 50 + 233 * 50 ) / 100 = 123

这样在Java中可以对以上计算方法封装成函数或类,以方便代码复用,对应的Java代码如下:

protected Color calculateAlphaValue(Color c1, Color c2, int alpha) { if (alpha < MIN_ALPHA) alpha = MIN_ALPHA; else if (alpha > MAX_ALPHA) alpha = MAX_ALPHA; int R = (c1.getRed() * (MAX_ALPHA - alpha) + c2.getRed() * alpha) / MAX_ALPHA; int G = (c1.getGreen() * (MAX_ALPHA - alpha) + c2.getGreen() * alpha) / MAX_ALPHA; int B = (c1.getBlue() * (MAX_ALPHA - alpha) + c2.getBlue() * alpha) / MAX_ALPHA; return new Color(R, G, B); }

 

本文地址:http://com.8s8s.com/it/it17035.htm