Search code examples
c#stringbrush

C# Brush to string


I search a way to save the color of a brush as a string. For example I have a Brush which has the color red. Now I want to write "red" in a textbox.

Thanks for any help.


Solution

  • If the Brush was created using a Color from System.Drawing.Color, then you can use the Color's Name property.

    Otherwise, you could just try to look up the color using reflection

    // hack
    var b = new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 235, 205));
    var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
                     where p.PropertyType.Equals(typeof(System.Drawing.Color))
                     let value = (System.Drawing.Color)p.GetValue(null, null)
                     where value.R == b.Color.R &&
                           value.G == b.Color.G &&
                           value.B == b.Color.B &&
                           value.A == b.Color.A
                     select p.Name).DefaultIfEmpty("unknown").First();
    
    // colorname == "BlanchedAlmond"
    

    or create a mapping yourself (and look the color up via a Dictionary), probably using one of many color tables around.

    Edit:

    You wrote a comment saying you use System.Windows.Media.Color, but you could still use System.Drawing.Color to look up the name of the color.

    var b = System.Windows.Media.Color.FromArgb(255, 255, 235, 205);
    var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
                     where p.PropertyType.Equals(typeof(System.Drawing.Color))
                     let value = (System.Drawing.Color)p.GetValue(null, null)
                     where value.R == b.R &&
                           value.G == b.G &&
                           value.B == b.B &&
                           value.A == b.A
                     select p.Name).DefaultIfEmpty("unknown").First();