我想基于对象的颜色值绘制的字符串,我认为这将是简单到只用spritebatch通常得出:如何在XNA中绘制颜色的字符串名称?
DrawString(Font, Color.ToString, Vector2, Colour)
然而,“Color.ToString”返回RGBA(X,Y ,z,a)特定颜色的值。 无论如何都要将RGBA颜色的属性名称(例如:“红色”)绘制到屏幕上,而无需通过案例进行处理以及不通过RGBA值确定颜色的内容;这将节省时间和编码空间。
我想基于对象的颜色值绘制的字符串,我认为这将是简单到只用spritebatch通常得出:如何在XNA中绘制颜色的字符串名称?
DrawString(Font, Color.ToString, Vector2, Colour)
然而,“Color.ToString”返回RGBA(X,Y ,z,a)特定颜色的值。 无论如何都要将RGBA颜色的属性名称(例如:“红色”)绘制到屏幕上,而无需通过案例进行处理以及不通过RGBA值确定颜色的内容;这将节省时间和编码空间。
如果您想限制您的选择为指定的颜色值,您可能需要改为使用System.Drawing.KnownColor
。 在任何情况下,如果要为具有名称的颜色指定颜色名称,则可以使用Color.Name
而不是Color.ToString()
,但只有在颜色是使用已知颜色而不是RGBA值构建的时才起作用。如果你需要查找一个已知的颜色名称,你可以写这样的功能,然后得到返回颜色的名称:
Public Function FindKnownColor(value As Color) As Color
For Each known In [Enum].GetValues(GetType(KnownColor))
Dim compare = Color.FromKnownColor(known)
If compare.ToArgb() = value.ToArgb() Then Return compare
Next
Return value
End Function
如果您需要优化您可以创建一个字典,其中键是ToArgb值,该值可以是此函数返回的颜色对象,也可以是该颜色的名称属性。
在XNA中Color类不是枚举,因此您必须使用反射来获取所有静态属性值及其名称。我在这里提供的示例创建一个静态字典,将Color值映射到其名称。字典将在第一次使用类/ ToName函数时初始化。
' Usage:
' Dim colorName = ColorExtensions.ToName(Color.Red)
Public NotInheritable Class ColorExtensions
Private Sub New()
End Sub
Private Shared ReadOnly ColorToString As New Dictionary(Of Color, [String])()
Shared Sub New()
' Get all the static properties on the XNA Color type
Dim properties = GetType(Color).GetProperties(BindingFlags.[Public] Or BindingFlags.[Static])
' Loop through all of the properties
For Each [property] As PropertyInfo In properties
' If the property's type is a Color...
If [property].PropertyType Is GetType(Color) Then
' Get the actual color value
Dim color = DirectCast([property].GetValue(Nothing, Nothing), Color)
' We have to actually check that the color has not already been assocaited
' Names will always be unique, however, some names map to the same color
If ColorToString.ContainsKey(color) = False Then
' Associate the color value with the property name
ColorToString.Add(color, [property].Name)
End If
End If
Next
End Sub
Public Shared Function ToName(color As Color) As [String]
' The string that stores the color's name
Dim name As [String] = Nothing
' Attempt to get the color name from the dictionary
If ColorToString.TryGetValue(color, name) Then
Return name
End If
' Return null since we didn't find it
Return Nothing
End Function
End Class
只是一个侧面说明,我不会在VB.NET中原生写入,所以我运行了一个从C#到VB.NET的转换器,然后用VB XNA游戏进行测试,以确保它正常工作。 – Trevor 2014-11-05 19:28:37
虽然它不会解决问题,但您的意思是编写'Color.ToString()'。 – gunr2171 2014-11-05 14:36:44
那么我写在VB.Net所以没有,这是不需要的语言。 – JimmyB 2014-11-05 14:38:38