2009-11-11 73 views
0

我有一個顏色A,我想通過使用顏色B轉換成C顏色。所以我想知道GDI +中的混合公式F,其中F = F(A,B )= C. A是 「底色」,而B是一個覆蓋顏色上述A,其與A一起產生C.GDI的混合公式+

乾杯,

//馬格努斯

+0

我假設B顏色是半透明的? – SLaks 2009-11-11 23:35:52

+0

如果您的意思是B的alpha值小於1,那麼:) – ralphtheninja 2009-11-11 23:50:27

回答

2

這被稱爲Alpha Blending

使用以下算法用於R,G和B分量,其中alpha是0和1之間

newColor = MAX(255, (1 - alpha) * background + alpha * overlay) 
+0

背景和疊加的單個alpha值?或者你的意思是(1-alpha_background)* background + alpha_overlay * overlay? – ralphtheninja 2009-11-11 23:52:11

+0

Aaah ok,背景在這裏完全不透明。 – ralphtheninja 2009-11-12 00:02:19

0

基本上(α,紅,綠,藍以0至1的範圍):

Result.Alpha = BackColor.Alpha + ForeColor.Alpha - (BackColor.Alpha * ForeColor.Alpha)
Result.Red =((ForeColor.Red * ForeColor.Alpha)+(BackColor.Red * BackColor.Alpha *(1 - ForeColor.Alpha)))/ Result.Alpha
(將'red'替換爲'green'和'blue'以獲得corr esponding函數)

對於32位顏色,在VB.NET(有點優化):

Shared Function Flatten(ByVal BackColor As Color, ByVal ForeColor As Color) As Color 
    If ForeColor.A = 0 Then Return BackColor ' Prevent division by zero 
    If ForeColor.A = 255 Then Return ForeColor ' Shortcut 

    Dim BackAlphaDbl As Single = CSng(BackColor.A) ' Convert to single to prevent in-calculation 8 bit overflow 
    Dim ForeAlphaDbl As Single = CSng(ForeColor.A) 

    Dim ForeAlphaNormalized As Single = ForeAlphaDbl/255 ' Precalculate for triple use 
    Dim BackcolorMultiplier As Single = BackAlphaDbl * (1 - ForeAlphaNormalized) ' Precalculate 

    Dim Alpha As Single = BackAlphaDbl + ForeAlphaDbl - BackAlphaDbl * ForeAlphaNormalized 

    Return Color.FromArgb(Alpha, (ForeColor.R * ForeAlphaDbl + BackColor.R * BackcolorMultiplier)/Alpha, (ForeColor.G * ForeAlphaDbl + BackColor.G * BackcolorMultiplier)/Alpha, (ForeColor.B * ForeAlphaDbl + BackColor.B * BackcolorMultiplier)/Alpha) 
End Function 

我用紙和筆這出,並通過與GDI重疊圖像+和測試所得顏色驗證它。這個函數和GDI +的唯一區別在於GDI +在前景阿爾法變化時上下不一致。這個功能更精確。