我想基於對象的顏色值繪製的字符串,我認爲這將是簡單到只用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