2012-01-05 91 views
8

如何從數學上計算不透明度?以數學方式計算不透明度值

Photoshop,CSS等中有不透明的值。實際上,這種不透明度是圖層的透明行爲。我們都知道。 但是它是如何計算的?有沒有計算不透明度的方程式?

通過設置不透明度值發生了什麼?

採取素色層的情況下:層1(前景層)和層2(背景層)

層1是紅色(說色值A)和第2層是白色的(說色值B) 。當我們將不透明度(比如說p)設置爲第1層時,我們可以放0.5或50%,並得到白色的紅色(比如顏色值X)。

獲取此值X我該怎麼做數學?

即。

X = (things which will be a relation containing p, A and B) 

我想知道確切的數學方程式來尋找X

另外,如果我有公式,顏色值本質上是十六進制的,所以用十六進制計算器可以得到正確的結果嗎?

回答

19

C1 = (R1,G1,B1)和C2 = (R2,G2,B2)組合成一個新的顏色C3,其中C2上的C1頂部重疊與不透明度p公式通常((1-p)R1 + p*R2, (1-p)*G1 + p*G2, (1-p)*B1 + p*B2)是。

有關更多信息,請參閱Wikipedia article on transparency

4

以下JavaScript給出了可以用於手動計算不透明度的顏色值的方法:

// caculateTransparentColor(foreground, background, opacity) 
var theColor = caculateTransparentColor('#ff0000', '#00ff00', 0.5) 
console.log(theColor); 
Returns: #808000 

代碼:

var COLOR_REGEX = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/; 
function colorHexToRGB(htmlColor) { 

    arrRGB = htmlColor.match(COLOR_REGEX); 
    if (arrRGB == null) { 
     alert("Invalid color passed, the color should be in the html format. Example: #ff0033"); 
    } 
    var red = parseInt(arrRGB[1], 16); 
    var green = parseInt(arrRGB[2], 16); 
    var blue = parseInt(arrRGB[3], 16); 
    return {"r":red, "g":green, "b":blue}; 
} 

function caculateTransparentColor(foregroundColor, backgroundColor, opacity) { 
    if (opacity < 0.0 || opacity > 1.0) { 
     alert("assertion, opacity should be between 0 and 1"); 
    } 
    opacity = opacity * 1.0; // to make it float 
    var foregroundRGB = colorHexToRGB(foregroundColor); 
    var backgroundRGB = colorHexToRGB(backgroundColor); 
    var finalRed = Math.round(backgroundRGB.r * (1-opacity) + foregroundRGB.r * opacity); 
    var finalGreen = Math.round(backgroundRGB.g * (1-opacity) + foregroundRGB.g * opacity); 
    var finalBlue = Math.round(backgroundRGB.b * (1-opacity) + foregroundRGB.b * opacity); 
    return colorRGBToHex(finalRed, finalGreen, finalBlue); 
} 

function colorRGBToHex(red, green, blue) { 
    if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { 
     alert("Invalid color value passed. Should be between 0 and 255."); 
    } 
    var formatHex = function(value) { 
     value = value + ""; 
     if (value.length == 1) { 
      return "0" + value; 
     } 
     return value; 
    } 
    hexRed = formatHex(red.toString(16)); 
    hexGreen = formatHex(green.toString(16)); 
    hexBlue = formatHex(blue.toString(16)); 

    return "#" + hexRed + hexGreen + hexBlue; 
} 
+0

謝謝! http://jsbin.com/OxEPEqo/2/edit - 我需要相反的,這是第二組輸入。 – Langdon 2013-08-28 20:02:36

+0

「caculateTransparentColor」方法似乎有前後翻轉的情況。它是'前景*不透明',而不是'前景*(1 - 不透明)'。提交編輯。 – 2014-05-05 19:06:40

0

式用於混合兩種透明的像素的結果:

C1 = [R1,G1,B1]是前景像素顏色。

C2 = [R2,G2,B2]是背景像素顏色。

p1是前景像素的不透明度百分比。

p2是背景像素的不透明度百分比。

New_Pixel_Color =(P1 * C1 + P2 * C2-P1 * P2 * C2)/(P1 + P2-P1 * P2)

New_Pixel_opacity = P1 + P2-P1 * P2

你可以測試並享受它!

+2

如果你想宣傳你的網站,你應該在你的個人資料中這樣做。 – 2014-02-01 00:45:51