2014-02-07 87 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

相关问题