如何在XNA中绘制颜色的字符串名称?

时间:2014-11-05 14:34:18

标签: vb.net colors xna

我想根据对象的颜色值绘制字符串,我认为用spritebatch正常绘制会很简单:

DrawString(Font, Color.ToString, Vector2, Colour)

但是,“Color.ToString”返回特定颜色的RGBA(x,y,z,a)值。 无论如何都要将RGBA颜色的属性名称(例如:“红色”)绘制到屏幕上,而不必处理整个案例以及不通过RGBA值确定颜色的内容;它可以节省时间和编码空间。

2 个答案:

答案 0 :(得分:0)

如果要将选择限制为命名颜色值,可能需要使用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值,该值是该函数返回的颜色对象,或者只是该颜色的name属性。

答案 1 :(得分:0)

在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