Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Brush to string

Tags:

string

c#

brush

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.

like image 545
Waronius Avatar asked Sep 07 '25 13:09

Waronius


2 Answers

What type of brush is this? If its drawing namespace, then brush is an abstract class.! For SolidBrush, do:

brush.Color.ToString()

Otherwise, get the color property and use ToString() method to convert color to its string representation.

like image 188
pathfinder666 Avatar answered Sep 09 '25 03:09

pathfinder666


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();
like image 37
sloth Avatar answered Sep 09 '25 03:09

sloth