从绿色到红色取决于值 [英] From green to red depending on the value
问题描述
我需要一个函数在 vb.net 中返回从红色(值 0)到绿色(值 100)的颜色.此外,我需要一种方法来发现字体的颜色应该是白色还是黑色,具体取决于背景颜色.
I need a function that returns a color from red (value 0) to green (value 100) in vb.net. Also I need a way to discover if the color of the font should be white or black, depending on the background color.
推荐答案
线性插值
我曾经同样需要在 winform 中的两种颜色之间进行线性插值
.我会做一个例外并分享这背后的代码,因为我认为它不仅对 OP 有用,而且对其他人也有用.
I once had the same need to do linearly interpolation
between two colors in a winform. I will do an exception and share the code behind this as I think it might be useful for not only the OP but others.
该函数接受 0.0
(0%) 到 1.0
范围内的 Single
值(100%).
The function accept a Single
value in the range 0.0
(0%) to 1.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
所以在你的情况下,它看起来像这样:
So in your case it will look like this:
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
,则应使用白色前色.
Regarding the part "white or black, depending on the background" you need to know the luminosity of the color. The following function returns 0 for a black and 240 for a white color. So if the luminosity of a given backcolor is <= 120
one should use a white forecolor.
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
这篇关于从绿色到红色取决于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!