Why is Color.IsNamedColor not working when I create a color using Color.FromArgb ()?

In my application, I allow the user to create a color and then show him the name or value of the color later. If the user selects red (full red, not red-ish), I want to show him "red". If he picks some weird color then the hex value will be fine. Here's some sample code that demonstrates the problem:

static string GetName(int r, int g, int b)
{
    Color c = Color.FromArgb(r, g, b);  // Note that specifying a = 255 doesn't make a difference
    if (c.IsNamedColor)
    {
        return c.Name;
    }
    else
    {
        // return hex value
    }
}

      

Even with very obvious colors like red IsNamedColor

, it never returns true. Looking at the ARGB values ​​for my color and Color.Red

, I don't see any difference. However, the call Color.Red.GetHashCode()

returns a different hash code than Color.FromArgb(255, 0, 0).GetHashCode()

.

How do I create a color using user-specified RGB values ​​and get the property Name

?

+2


source to share


2 answers


From MSDN.

Property Value Type: System.Boolean
true if this color was generated using the FromName method or the FromKnownColor method; otherwise, false.



You can build a map from all KnownColor

rgb tuples for the names I assume.

+2


source


This is probably not the fastest method, but it works. The colors don't have to exactly match the name you want to choose, for example. GetColorName(Color.FromArgb(254, 254, 0));

will still return yellow.

I deliberately ditched access modifiers



Color[] KnownColors; 

void Init (){
    KnownColors = (from colorInfo in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.CreateInstance |BindingFlags.Public)
                   where colorInfo.PropertyType == typeof (Color)
                   select (Color)colorInfo.GetValue(null, null)).Where (c => c.A != 0).ToArray();
}

string GetColorName(Color inColour)
{

    // I'm just getting started on LINQ so im not
    // sure how to do this with it (Maybe some one can help out with that)

    int MinDistance = int.MaxValue;

    Color closestKnown = Color.Black;
    foreach (var c in KnownColors)
    {
        var d = ColorDistance(c, inColour);

        if (d < MinDistance){
            closestKnown = c;
            MinDistance = d;
        }
    }

    return closestKnown.Name;
}


int ColorDistance(Color c1, Color c2)
    {

    var ad = (c1.A - c2.A);
    var rd = (c1.R - c2.R);
    var gd = (c1.G - c2.G);
    var bd = (c1.B - c2.B);

    return (ad * ad) + (rd * rd) + (gd * gd) + (bd * bd);
}

      

0


source







All Articles