0

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?

4
  • Do you mean you have to present the user with these options in UI, like for a color picker or something? Commented Apr 14, 2016 at 18:00
  • The user will enter a color value, either in hex format "#F00", or System Color "Red". If the hex value they entered in is a system color, I need to output the System color instead of the hex value. Commented Apr 14, 2016 at 18:04
  • Have you attempted any code yet? You should show us what you have. Commented Apr 14, 2016 at 18:19
  • System colors are variable and not alwayse the same, do you mean named colors such as red, green, etc??? Commented Apr 14, 2016 at 21:00

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.