2014-02-07 86 views
-4

我需要一個函數,它可以在vb.net中從紅色(值爲0)到綠色(值爲100)返回一種顏色。此外,我需要一種方法來發現字體的顏色應該是白色還是黑色,具體取決於背景顏色。從綠色到紅色取決於值

+2

你知道演習,告訴我們你到目前爲止做了什麼。這不是一個代碼工廠。說到這裏,你要找的東西就像'XNA' [Color.Lerp](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.color。 lerp(v = xnagamestudio.31).aspx)方法。 –

回答

2

線性插值

我曾經有過同樣需要做到色彩linearly interpolation兩者之間的WinForm的。我會做一個例外,並分享背後的代碼,因爲我認爲它不僅可以用於OP,還可以用於其他用途。

該函數接受範圍0.0(0%)一個Single1.0(100%)

Public Shared Function Lerp(ByVal color1 As Color, ByVal color2 As Color, ByVal amount As Single) As Color 
    Const bitmask As Single = 65536.0! 
    Dim n As UInteger = CUInt(Math.Round(CDbl(Math.Max(Math.Min((amount * bitmask), bitmask), 0.0!)))) 
    Dim r As Integer = (CInt(color1.R) + (((CInt(color2.R) - CInt(color1.R)) * CInt(n)) >> 16)) 
    Dim g As Integer = (CInt(color1.G) + (((CInt(color2.G) - CInt(color1.G)) * CInt(n)) >> 16)) 
    Dim b As Integer = (CInt(color1.B) + (((CInt(color2.B) - CInt(color1.B)) * CInt(n)) >> 16)) 
    Dim a As Integer = (CInt(color1.A) + (((CInt(color2.A) - CInt(color1.A)) * CInt(n)) >> 16)) 
    Return Color.FromArgb(a, r, g, b) 
End Function 

所以你的情況就會是這樣的:

Dim value As Integer = 'A value in the range 0 - 100 
Dim newColor As Color = Lerp(Color.Red, Color.Green, If((value > 0I), (Math.Min(Math.Max(CSng(value), 0.0!), 100.0!)/100.0!), 0.0!)) 

光度

關於部分「白色或黑色,取決於背景」你需要知道的顏色的亮度。以下函數返回0表示黑色,240表示白色。因此,如果給定背景色的光度爲<= 120,則應使用白色前景色。

Public Shared Function GetLuminosity(c As Color) As Integer 
    Return CInt((((Math.Max(Math.Max(CInt(c.R), CInt(c.G)), CInt(c.B)) + Math.Min(Math.Min(CInt(c.R), CInt(c.G)), CInt(c.B))) * 240) + 255)/510I) 
End Function 
+0

另一種比這個更糟的方法是使用'Drawing2D.LinearGradientBrush',將其轉換爲位圖並使用方法'GetPixel'。知道這個功能,這是一個荒謬的使用這種方式... – Nizam

相關問題