在Java中合并两个带透明度的颜色整数

3

我正在处理一个项目,需要手动计算我正在使用的每个像素颜色并将两者组合在一起。

底部像素颜色始终具有100%的不透明度,但顶部则没有,并且可以包含任何透明度级别。

我正试图创建一个算法来合并颜色,以便透明度会有实际效果,以下是我目前拥有的:

public static int combine(int bottom, int top) {

    int tAlpha = Color.alpha(top);

    if (tAlpha < 255 && tAlpha > 0) {

        int tRed = Color.red(top);
        int tGreen = Color.green(top);
        int tBlue = Color.blue(top);

        int bRed = Color.red(bottom);
        int bGreen = Color.green(bottom);
        int bBlue = Color.blue(bottom);

        int cRed = (int) (bRed + (tRed * (Float.valueOf(tAlpha) / 255)));
        int cGreen = (int) (bGreen + (tGreen * (Float.valueOf(tAlpha) / 255)));
        int cBlue = (int) (bBlue + (tBlue * (Float.valueOf(tAlpha) / 255)));

        cRed = (cRed <= 255) ? cRed : 255;
        cGreen = (cGreen <= 255) ? cGreen : 255;
        cBlue = (cBlue <= 255) ? cBlue : 255;

        return Color.argb(255, cRed, cGreen, cBlue);

    } else if (tAlpha == 0) {

        return bottom;

    } else if (tAlpha == 255) {

        return top;

    } else {

        return 0;

    }

}

我遇到的问题是,某些像素的aRGB值为(???, 0, 0, 0),在这段代码中,底部像素的颜色将占主导地位,而不是通过alpha值变暗。如何改进这个问题?有任何解决方案都将不胜感激。
1个回答

6

使用标准的Alpha混合公式,您应该计算输出颜色:

cRed = (tRed * tAlpha + bRed * (255 - tAlpha)) / 255;

同样的,对于蓝色和绿色通道也是这样处理。根据 tAlpha 在范围 [0, 255] 内的位置,将每个 rgb 通道设置为相应顶部和底部通道值的线性插值。我认为你不必担心夹紧;每个分量都会保持在范围 [0, 255] 内。

当然,对于特殊情况tAlpha == 0tAlpha == 255,你可以采取快捷方式。


1
啊,找不到这个公式了。之前可是完美运行的。谢谢。 - Matt Clark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接