Reputation: 228
I need to change the string value "#FFF"
to the string "white"
Or "#FF0000"
to "red"
.
In the case that the hex value is not a system color, it would just use the hex value. "#906"
would output "#906"
.
Any ideas?
Upvotes: 0
Views: 408
Reputation: 1877
If you just want to map the system colors you could do something like this. Note that this also returns values for the system such as WindowBrush etc, which I filter out using the continue
check. Note that I'm using c# 6 string interpolations here but you can concatenate however you like.
using Color = System.Drawing.Color;
...
{
string input = $"#ff{myTextBox.Text}"; // let the user enter just the digits
input = input.ToLower(); // Needs to be lowercase, or you could use a case invariant check later
string name;
KnownColor[] values = (KnownColor[])Enum.GetValues(typeof(KnownColor));
for(int i =0; i <values.Length; i++)
{
if (i <= 25 || i >= 167) continue; // Eliminate default wpf control colors
int RealColor = Color.FromKnownColor(values[i]).ToArgb();
string ColorHex = $"{RealColor:x6}";
if ($"#{ ColorHex }"== input)
{
name = values[i].ToString();
break;
}
}
}
Honestly though I would just create my own Dictionary
of values and do a simple lookup, eg.:
var myColors = new Dictionary<string, string>
{
{"#FF000000", "Black"},
...
};
string colorName;
if (myColors.ContainsKey(myTextBox.Text))
colorName = myColors[myTextBox.Text];
else
colorName = myTextBox.Text;
Upvotes: 1