簡體   English   中英

將兩個Color整數與Java中的透明度組合在一起

[英]Combining two Color integers with transparency in Java

我正在開發一個項目,要求我手動計算我正在使用的每個像素顏色的顏色,並將兩個顏色組合在一起。

底部像素顏色將始終具有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混合公式 ,您應該使用以下方法計算輸出顏色:

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

同樣適用於藍色和綠色通道。 這只是根據tAlpha在[0,255]范圍內的位置將每個rgb通道設置為相應的頂部和底部通道值的線性插值。 我不相信你需要擔心夾緊; 每個組件將保持在[0,255]范圍內。

當然,您可以針對tAlpha == 0tAlpha == 255的特殊情況選擇快捷方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM