How to convert RGB value to color name in Silverlight 4.0?
The code :
Dim myColor As Color = Colors.Red
Dim colorName As String = myColor.ToString()
Results in :
#FFFF0000
when printing colorName to screen.
Is it possible to get the color name in Sil开发者_如何学运维verlight without making a select case on the RGB values?
I developed a very useful ColorFromString class that does exactly that. You can get the code here ColorFromString for Silverlight or NET, or here:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Media;
namespace ClassLibrary
{
public static class ColorFromString
{
private static Dictionary<string, Color> namedColors =
new Dictionary<string, Color>();
// Extension for string
public static Color ToColor(this string value)
{
if (value == null)
return Colors.Red;
// Named Colors
string valueLower = value.ToLower();
if (namedColors.ContainsKey(valueLower))
return namedColors[valueLower];
// #ARGB and #RGB Hex Colors
if (value[0] == '#')
value = value.Remove(0, 1);
int length = value.Length;
if ((length == 6 || length == 8) && IsHexColor(value))
{
if (length == 8)
return Color.FromArgb(
byte.Parse(value.Substring(0, 2), NumberStyles.HexNumber),
byte.Parse(value.Substring(2, 2), NumberStyles.HexNumber),
byte.Parse(value.Substring(4, 2), NumberStyles.HexNumber),
byte.Parse(value.Substring(6, 2), NumberStyles.HexNumber));
if (length == 6)
return Color.FromArgb(0xff,
byte.Parse(value.Substring(0, 2), NumberStyles.HexNumber),
byte.Parse(value.Substring(2, 2), NumberStyles.HexNumber),
byte.Parse(value.Substring(4, 2), NumberStyles.HexNumber));
}
// A,R,G,B and R,G,B Colors
string[] argb = value.Split(
new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (argb != null)
{
if (argb.Length == 4)
return Color.FromArgb(
byte.Parse(argb[0]), byte.Parse(argb[1]), byte.Parse(argb[2]),
byte.Parse(argb[3]));
if (argb.Length == 3)
return Color.FromArgb(0xff,
byte.Parse(argb[0]), byte.Parse(argb[1]), byte.Parse(argb[2]));
}
return Colors.Red;
}
private static bool IsHexColor(string value)
{
if (value == null)
return false;
foreach (char c in value.ToCharArray())
if (!Uri.IsHexDigit(c))
return false;
return true;
}
static ColorFromString()
{
namedColors.Add("aliceblue", ToColor("#f0f8ff"));
namedColors.Add("antiquewhite", ToColor("#faebd7"));
namedColors.Add("aqua", ToColor("#00ffff"));
namedColors.Add("aquamarine", ToColor("#7fffd4"));
namedColors.Add("azure", ToColor("#f0ffff"));
namedColors.Add("beige", ToColor("#f5f5dc"));
namedColors.Add("bisque", ToColor("#ffe4c4"));
namedColors.Add("black", ToColor("#000000"));
namedColors.Add("blanchedalmond", ToColor("#ffebcd"));
namedColors.Add("blue", ToColor("#0000ff"));
namedColors.Add("blueviolet", ToColor("#8a2be2"));
namedColors.Add("brown", ToColor("#a52a2a"));
namedColors.Add("burlywood", ToColor("#deb887"));
namedColors.Add("cadetblue", ToColor("#5f9ea0"));
namedColors.Add("chartreuse", ToColor("#7fff00"));
namedColors.Add("chocolate", ToColor("#d2691e"));
namedColors.Add("coral", ToColor("#ff7f50"));
namedColors.Add("cornflowerblue", ToColor("#6495ed"));
namedColors.Add("cornsilk", ToColor("#fff8dc"));
namedColors.Add("crimson", ToColor("#dc143c"));
namedColors.Add("cyan", ToColor("#00ffff"));
namedColors.Add("darkblue", ToColor("#00008b"));
namedColors.Add("darkcyan", ToColor("#008b8b"));
namedColors.Add("darkgoldenrod", ToColor("#b8860b"));
namedColors.Add("darkgray", ToColor("#a9a9a9"));
namedColors.Add("darkgreen", ToColor("#006400"));
namedColors.Add("darkkhaki", ToColor("#bdb76b"));
namedColors.Add("darkmagenta", ToColor("#8b008b"));
namedColors.Add("darkolivegreen", ToColor("#556b2f"));
namedColors.Add("darkorange", ToColor("#ff8c00"));
namedColors.Add("darkorchid", ToColor("#9932cc"));
namedColors.Add("darkred", ToColor("#8b0000"));
namedColors.Add("darksalmon", ToColor("#e9967a"));
namedColors.Add("darkseagreen", ToColor("#8fbc8f"));
namedColors.Add("darkslateblue", ToColor("#483d8b"));
namedColors.Add("darkslategray", ToColor("#2f4f4f"));
namedColors.Add("darkturquoise", ToColor("#00ced1"));
namedColors.Add("darkviolet", ToColor("#9400d3"));
namedColors.Add("deeppink", ToColor("#ff1493"));
namedColors.Add("deepskyblue", ToColor("#00bfff"));
namedColors.Add("dimgray", ToColor("#696969"));
namedColors.Add("dodgerblue", ToColor("#1e90ff"));
namedColors.Add("firebrick", ToColor("#b22222"));
namedColors.Add("floralwhite", ToColor("#fffaf0"));
namedColors.Add("forestgreen", ToColor("#228b22"));
namedColors.Add("fuchsia", ToColor("#ff00ff"));
namedColors.Add("gainsboro", ToColor("#dcdcdc"));
namedColors.Add("ghostwhite", ToColor("#f8f8ff"));
namedColors.Add("gold", ToColor("#ffd700"));
namedColors.Add("goldenrod", ToColor("#daa520"));
namedColors.Add("gray", ToColor("#808080"));
namedColors.Add("green", ToColor("#008000"));
namedColors.Add("greenyellow", ToColor("#adff2f"));
namedColors.Add("honeydew", ToColor("#f0fff0"));
namedColors.Add("hotpink", ToColor("#ff69b4"));
namedColors.Add("indianred", ToColor("#cd5c5c"));
namedColors.Add("indigo", ToColor("#4b0082"));
namedColors.Add("ivory", ToColor("#fffff0"));
namedColors.Add("khaki", ToColor("#f0e68c"));
namedColors.Add("lavender", ToColor("#e6e6fa"));
namedColors.Add("lavenderblush", ToColor("#fff0f5"));
namedColors.Add("lawngreen", ToColor("#7cfc00"));
namedColors.Add("lemonchiffon", ToColor("#fffacd"));
namedColors.Add("lightblue", ToColor("#add8e6"));
namedColors.Add("lightcoral", ToColor("#f08080"));
namedColors.Add("lightcyan", ToColor("#e0ffff"));
namedColors.Add("lightgoldenrodyellow", ToColor("#fafad2"));
namedColors.Add("lightgreen", ToColor("#90ee90"));
namedColors.Add("lightgrey", ToColor("#d3d3d3"));
namedColors.Add("lightpink", ToColor("#ffb6c1"));
namedColors.Add("lightsalmon", ToColor("#ffa07a"));
namedColors.Add("lightseagreen", ToColor("#20b2aa"));
namedColors.Add("lightskyblue", ToColor("#87cefa"));
namedColors.Add("lightslategray", ToColor("#778899"));
namedColors.Add("lightsteelblue", ToColor("#b0c4de"));
namedColors.Add("lightyellow", ToColor("#ffffe0"));
namedColors.Add("lime", ToColor("#00ff00"));
namedColors.Add("limegreen", ToColor("#32cd32"));
namedColors.Add("linen", ToColor("#faf0e6"));
namedColors.Add("magenta", ToColor("#ff00ff"));
namedColors.Add("maroon", ToColor("#800000"));
namedColors.Add("mediumaquamarine", ToColor("#66cdaa"));
namedColors.Add("mediumblue", ToColor("#0000cd"));
namedColors.Add("mediumorchid", ToColor("#ba55d3"));
namedColors.Add("mediumpurple", ToColor("#9370db"));
namedColors.Add("mediumseagreen", ToColor("#3cb371"));
namedColors.Add("mediumslateblue", ToColor("#7b68ee"));
namedColors.Add("mediumspringgreen", ToColor("#00fa9a"));
namedColors.Add("mediumturquoise", ToColor("#48d1cc"));
namedColors.Add("mediumvioletred", ToColor("#c71585"));
namedColors.Add("midnightblue", ToColor("#191970"));
namedColors.Add("mintcream", ToColor("#f5fffa"));
namedColors.Add("mistyrose", ToColor("#ffe4e1"));
namedColors.Add("moccasin", ToColor("#ffe4b5"));
namedColors.Add("navajowhite", ToColor("#ffdead"));
namedColors.Add("navy", ToColor("#000080"));
namedColors.Add("oldlace", ToColor("#fdf5e6"));
namedColors.Add("olive", ToColor("#808000"));
namedColors.Add("olivedrab", ToColor("#6b8e23"));
namedColors.Add("orange", ToColor("#ffa500"));
namedColors.Add("orangered", ToColor("#ff4500"));
namedColors.Add("orchid", ToColor("#da70d6"));
namedColors.Add("palegoldenrod", ToColor("#eee8aa"));
namedColors.Add("palegreen", ToColor("#98fb98"));
namedColors.Add("paleturquoise", ToColor("#afeeee"));
namedColors.Add("palevioletred", ToColor("#db7093"));
namedColors.Add("papayawhip", ToColor("#ffefd5"));
namedColors.Add("peachpuff", ToColor("#ffdab9"));
namedColors.Add("peru", ToColor("#cd853f"));
namedColors.Add("pink", ToColor("#ffc0cb"));
namedColors.Add("plum", ToColor("#dda0dd"));
namedColors.Add("powderblue", ToColor("#b0e0e6"));
namedColors.Add("purple", ToColor("#800080"));
namedColors.Add("red", ToColor("#ff0000"));
namedColors.Add("rosybrown", ToColor("#bc8f8f"));
namedColors.Add("royalblue", ToColor("#4169e1"));
namedColors.Add("saddlebrown", ToColor("#8b4513"));
namedColors.Add("salmon", ToColor("#fa8072"));
namedColors.Add("sandybrown", ToColor("#f4a460"));
namedColors.Add("seagreen", ToColor("#2e8b57"));
namedColors.Add("seashell", ToColor("#fff5ee"));
namedColors.Add("sienna", ToColor("#a0522d"));
namedColors.Add("silver", ToColor("#c0c0c0"));
namedColors.Add("skyblue", ToColor("#87ceeb"));
namedColors.Add("slateblue", ToColor("#6a5acd"));
namedColors.Add("slategray", ToColor("#708090"));
namedColors.Add("snow", ToColor("#fffafa"));
namedColors.Add("springgreen", ToColor("#00ff7f"));
namedColors.Add("steelblue", ToColor("#4682b4"));
namedColors.Add("tan", ToColor("#d2b48c"));
namedColors.Add("teal", ToColor("#008080"));
namedColors.Add("thistle", ToColor("#d8bfd8"));
namedColors.Add("tomato", ToColor("#ff6347"));
namedColors.Add("turquoise", ToColor("#40e0d0"));
namedColors.Add("violet", ToColor("#ee82ee"));
namedColors.Add("wheat", ToColor("#f5deb3"));
namedColors.Add("white", ToColor("#ffffff"));
namedColors.Add("whitesmoke", ToColor("#f5f5f5"));
namedColors.Add("yellow", ToColor("#ffff00"));
namedColors.Add("yellowgreen", ToColor("#9acd32"));
}
}
}
The two colors may not look close, but there are only 140 "named" colors out of 16,777,216 possible combinations (256 * 256 * 256).
It is difficult to look at the RGB values and make any conclusions regarding the color matching.
'GetNearest...
' http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/b2d491ac-4031-46d6-bccb-8bf9a46c2289
' http://www.eggheadcafe.com/conversation.aspx?messageid=31472401&threadid=31472286
Imports System.Drawing
Imports System.Reflection
Imports System.Runtime.CompilerServices
Namespace Drawing
<HideModuleName()> _
Public Module ColorExtensions
''' <summary>
''' Gets the <see cref="System.Drawing.Color.Name">System.Drawing.Color.Name</see> of the closest matching color.
''' </summary>
''' <example>
''' <code>
''' Private Sub Example()
''' Dim oColor As Color = Color.FromName(GetNearestName(Color.FromArgb(255, 255, 255, 0)))
''' Debug.Assert(oColor.Name = "Yellow")
''' End Sub
''' </code>
''' </example>
<Extension()> _
Public Function GetNearestName(ByVal unknownColor As Color) As String
'short-circut
If unknownColor.IsNamedColor Then
Return unknownColor.Name
End If
Dim oBestMatch As ColorName = GetNearestNameInternal(unknownColor)
Return oBestMatch.Name
End Function
''' <summary>
''' Gets the <see cref="System.Drawing.KnownColor">System.Drawing.KnownColor</see> of the closest matching known color.
''' </summary>
''' <example>
''' <code>
''' Private Sub Example()
''' Dim oColor As Color = Color.FromKnownColor(GetNearestKnownColor(Color.FromArgb(255, 255, 255, 0)))
''' Debug.Assert(oColor.Name = "Yellow")
''' End Sub
''' </code>
''' </example>
<Extension()> _
Public Function GetNearestKnownColor(ByVal unknownColor As Color) As KnownColor
'short-circut
If unknownColor.IsKnownColor Then
Return unknownColor.ToKnownColor
End If
Dim oBestMatch As ColorName = GetNearestKnownColorInternal(unknownColor)
Return oBestMatch.Color.ToKnownColor
End Function
<DebuggerDisplay("Name={Color.Name}, Distance={Distance}, ARGB=({Color.A}, {Color.R}, {Color.G}, {Color.B})")> _
Friend Structure ColorName
Public Name As String
Public Color As Color
Public Distance As Double
''' <summary>
''' Returns RGB=(212,208,200)
''' </summary>
Public Function ToRGBString() As String
Return String.Format("RGB=({0},{1},{2})", Color.R, Color.G, Color.B)
End Function
End Structure
Friend Function GetNearestNameInternal(ByVal unknownColor As Color) As ColorName
Dim oBestMatch As ColorName = Nothing
Dim nClosestDistance As Double = Double.MaxValue
Dim oBindingFlags As BindingFlags = _
BindingFlags.DeclaredOnly Or _
BindingFlags.Public Or _
BindingFlags.Static
For Each oProperty As PropertyInfo In GetType(Color).GetProperties(oBindingFlags)
Dim oNamedColor As Color = DirectCast(oProperty.GetValue(Nothing, Nothing), Color)
Dim nDistance As Double
nDistance = System.Math.Sqrt( _
(CInt(unknownColor.R) - oNamedColor.R) ^ 2 + _
(CInt(unknownColor.G) - oNamedColor.G) ^ 2 + _
(CInt(unknownColor.B) - oNamedColor.B) ^ 2)
nDistance = System.Math.Sqrt(nDistance / 3)
If nDistance < nClosestDistance Then
nClosestDistance = nDistance
oBestMatch.Name = oProperty.Name
oBestMatch.Distance = nDistance
oBestMatch.Color = oNamedColor
End If
Next
Return oBestMatch
End Function
Friend Function GetNearestKnownColorInternal(ByVal unknownColor As Color) As ColorName
Dim oBestMatch As ColorName = Nothing
Dim nClosestDistance As Double = Double.MaxValue
For Each sColorName As String In [Enum].GetNames(GetType(KnownColor))
Dim oNamedColor As Color = Color.FromName(sColorName)
Dim nDistance As Double
nDistance = System.Math.Sqrt( _
(CInt(unknownColor.R) - oNamedColor.R) ^ 2 + _
(CInt(unknownColor.G) - oNamedColor.G) ^ 2 + _
(CInt(unknownColor.B) - oNamedColor.B) ^ 2)
nDistance = System.Math.Sqrt(nDistance / 3)
If nDistance < nClosestDistance Then
nClosestDistance = nDistance
oBestMatch.Name = oNamedColor.Name
oBestMatch.Distance = nDistance
oBestMatch.Color = oNamedColor
End If
Next
Return oBestMatch
End Function
#Region " Conditional Testing for GetNearest... Methods "
<Conditional("DEBUG")> _
Friend Sub TestGetNearest()
'from immediate window
' ColorExtensions.Test
'
'Results based on "Windows XP" default theme, with the display name of "Windows XP style'.
'
'Windows XP style
' ActiveBorder, RGB=(212,208,200); LightGray, RGB=(211,211,211); ActiveBorder, RGB=(212,208,200)
' ActiveCaption, RGB=(0,84,227); RoyalBlue, RGB=(65,105,225); ActiveCaption, RGB=(0,84,227)
' ActiveCaptionText, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' AppWorkspace, RGB=(128,128,128); Gray, RGB=(128,128,128); AppWorkspace, RGB=(128,128,128)
' Control, RGB=(236,233,216); AntiqueWhite, RGB=(250,235,215); Control, RGB=(236,233,216)
' ControlDark, RGB=(172,168,153); DarkGray, RGB=(169,169,169); ControlDark, RGB=(172,168,153)
' ControlDarkDark, RGB=(113,111,100); DimGray, RGB=(105,105,105); ControlDarkDark, RGB=(113,111,100)
' ControlLight, RGB=(241,239,226); Beige, RGB=(245,245,220); ControlLight, RGB=(241,239,226)
' ControlLightLight, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' ControlText, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' Desktop, RGB=(0,78,152); Teal, RGB=(0,128,128); Desktop, RGB=(0,78,152)
' GrayText, RGB=(172,168,153); DarkGray, RGB=(169,169,169); ControlDark, RGB=(172,168,153)
' Highlight, RGB=(49,106,197); RoyalBlue, RGB=(65,105,225); Highlight, RGB=(49,106,197)
' HighlightText, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' HotTrack, RGB=(0,0,128); Navy, RGB=(0,0,128); HotTrack, RGB=(0,0,128)
' InactiveBorder, RGB=(212,208,200); LightGray, RGB=(211,211,211); ActiveBorder, RGB=(212,208,200)
' InactiveCaption, RGB=(122,150,223); CornflowerBlue, RGB=(100,149,237); InactiveCaption, RGB=(122,150,223)
' InactiveCaptionText, RGB=(216,228,248); Lavender, RGB=(230,230,250); InactiveCaptionText, RGB=(216,228,248)
' Info, RGB=(255,255,225); LightYellow, RGB=(255,255,224); Info, RGB=(255,255,225)
' InfoText, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' Menu, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' MenuText, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' ScrollBar, RGB=(212,208,200); LightGray, RGB=(211,211,211); ActiveBorder, RGB=(212,208,200)
' Window, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' WindowFrame, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' WindowText, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' Transparent, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' Black, RGB=(0,0,0); Black, RGB=(0,0,0); ControlText, RGB=(0,0,0)
' Gray, RGB=(128,128,128); Gray, RGB=(128,128,128); AppWorkspace, RGB=(128,128,128)
' Navy, RGB=(0,0,128); Navy, RGB=(0,0,128); HotTrack, RGB=(0,0,128)
' White, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' ButtonFace, RGB=(236,233,216); AntiqueWhite, RGB=(250,235,215); Control, RGB=(236,233,216)
' ButtonHighlight, RGB=(255,255,255); Transparent, RGB=(255,255,255); ActiveCaptionText, RGB=(255,255,255)
' ButtonShadow, RGB=(172,168,153); DarkGray, RGB=(169,169,169); ControlDark, RGB=(172,168,153)
' GradientActiveCaption, RGB=(61,149,255); DodgerBlue, RGB=(30,144,255); GradientActiveCaption, RGB=(61,149,255)
' GradientInactiveCaption, RGB=(157,185,235); LightSteelBlue, RGB=(176,196,222); GradientInactiveCaption, RGB=(157,185,235)
' MenuBar, RGB=(236,233,216); AntiqueWhite, RGB=(250,235,215); Control, RGB=(236,233,216)
' MenuHighlight, RGB=(49,106,197); RoyalBlue, RGB=(65,105,225); Highlight, RGB=(49,106,197)
'
Debug.WriteLine(System.Windows.Forms.VisualStyles.VisualStyleInformation.DisplayName)
For Each sKnownColorName As String In [Enum].GetNames(GetType(KnownColor))
Dim oBaseColor As New ColorName
oBaseColor.Name = sKnownColorName
oBaseColor.Color = Color.FromName(sKnownColorName)
Dim oTestColor As Color = Color.FromArgb(255, oBaseColor.Color.R, oBaseColor.Color.G, oBaseColor.Color.B)
Dim oNearestNamed As ColorName = GetNearestNameInternal(oTestColor)
Dim oNearestKnown As ColorName = GetNearestKnownColorInternal(oTestColor)
'results will vary due to the current display theme properties
If oNearestNamed.Name <> oNearestKnown.Name Then
Debug.Write("' ")
Debug.Write(oBaseColor.Name)
Debug.Write(", ")
Debug.Write(oBaseColor.ToRGBString)
Debug.Write("; ")
Debug.Write(oNearestNamed.Name)
Debug.Write(", ")
Debug.Write(oNearestNamed.ToRGBString)
Debug.Write("; ")
Debug.Write(oNearestKnown.Name)
Debug.Write(", ")
Debug.Write(oNearestKnown.ToRGBString)
Debug.WriteLine("")
End If
Next
End Sub
''' <summary>
''' Dump all the Is... Properties
''' <example>
''' Current ActiveBorder is (255, 212, 208, 200)
''' Color.FromArgb(255, 212, 208, 200) 'ActiveBorder
''' Color.FromName("Yellow") '255, 255, 0
''' Color.FromArgb(255, 255, 255, 0) 'Yellow
''' </example>
''' </summary>
<Extension()> _
<Conditional("DEBUG")> _
Friend Sub BreakOnIsProperties(ByVal color As Color)
Dim I As Color = color.FromArgb(color.A, color.R, color.G, color.B)
If I.IsEmpty Then
Stop
End If
If I.IsKnownColor Then
Stop
End If
If I.IsNamedColor Then
Stop
End If
If I.IsSystemColor Then
Stop
End If
End Sub
#End Region
End Module
End Namespace
精彩评论