【问题标题】:From green to red depending on the value [closed]从绿色到红色取决于值[关闭]
【发布时间】:2014-02-07 06:17:14
【问题描述】:

我需要一个在 vb.net 中返回从红色(值 0)到绿色(值 100)的颜色的函数。我还需要一种方法来发现字体的颜色应该是白色还是黑色,具体取决于背景颜色。

【问题讨论】:

  • 你知道这个练习,告诉我们你到目前为止做了什么。这不是代码工厂。话虽如此,您正在寻找的是类似于 XNA Color.Lerp 方法。

标签: vb.net winforms


【解决方案1】:

线性插值

我曾经同样需要在 winform 中的两种颜色之间执行linearly interpolation。我会做一个例外并分享这背后的代码,因为我认为它可能不仅对 OP 有用,而且对其他人有用。

该函数接受0.0 (0%)1.0 (100%) 范围内的Single 值。

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

【讨论】:

  • 另一种方法,肯定比这个更糟糕,是使用Drawing2D.LinearGradientBrush,将其转换为位图并使用方法GetPixel。在这里知道这个功能,用这种方式实在是太荒唐了……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2014-06-18
  • 1970-01-01
  • 2013-09-27
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多