Reputation: 363
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.
Upvotes: 4
Views: 6462
Reputation: 3280
I had a object of System.Drawing.Brush and the color information is not accessible. It couldn't be case to type color either. It is possible to cast this to SolidBrush where the color information is available. I was able to cast my Brush color
object to a SolidBrush and then pull the name from the color this way.
((SolidBrush)color).Color.Name
Upvotes: 0
Reputation: 101142
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();
Upvotes: 2
Reputation: 189
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.
Upvotes: 3
Reputation: 116
Basically I'll post what was already answered.
string color = textBox1.Text;
// best, using Color's static method
Color red1 = Color.FromName(color);
// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString(color);
// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty(color).GetValue(null, null);
// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString(color);
Original answer: Convert string to Brushes/Brush color name in C#
Upvotes: 0