Convert String to Brushes/Brush Color Name in C#

Convert string to Brushes/Brush color name in C#

Recap of all previous answers, different ways to convert a string to a Color or Brush:

// best, using Color's static method
Color red1 = Color.FromName("Red");

// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString("Red");

// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);

// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");

Choose Brush by name

Use BrushConverter from the System.ComponentModel namespace:

BrushConverter conv = new BrushConverter();

You can use a color name:

SolidColorBrush brush = conv.ConvertFromString("Red") as SolidColorBrush;

You can also use an RGB value:

SolidColorBrush brush = conv.ConvertFromString("#0000FF") as SolidColorBrush;

How to convert color code into media.brush?

You could use the same mechanism the XAML reading system uses: Type converters

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

convert from Color to brush

This is for Color to Brush....

you can't convert it, you have to make a new brush....

SolidColorBrush brush = new SolidColorBrush( myColor );

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

How to get brushes color?

Below code illustrates a Button Click that changes the color of Button and Color of Button is stored in a String

 private void button1_Click(object sender, EventArgs e)
{
Brush brush = new SolidBrush(Color.Red);
button1.BackColor = ((SolidBrush)brush).Color;

string getColor;
getColor = button1.BackColor.ToString();
MessageBox.Show($"Color of Button1 " + getColor);

}

OR

private void button1_Click(object sender, EventArgs e)
{
Brush brush1 = Brushes.Red;
button1.BackColor = ((SolidBrush)brush1).Color;

string getColor1;
getColor1 = button1.BackColor.ToString();
MessageBox.Show($"Color of Button1 " + getColor1);

//Similarly store other button colors in a string
string getColor2 = "Orange"; string getColor3 = "Blue";

//Store these string value in a list
List<string> colors = new List<string>();
colors.Add(getColor1);
colors.Add(getColor2);
colors.Add(getColor3);
foreach (string color in colors) { MessageBox.Show(color); }
}

enter image description here

C# Brush to string

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();

Casting a string to a Brush object

If you need the properties in a list, I suggest you use List<object>. Since all classes in .NET derive from the object class, casting will be a lot more logic than casting a string to an object. Since you're using a list of objects, you don't need a class anymore to hold the properties. Also, you can use the object initializer to create the list instead of calling the Add() method every time. The assignment of the list will look like:

List<object> properties = new List<object>
{
backgroundColor,
textColor,
timeOffset,
dateOffset,
title,
showTitle,
showText
};

And now you can pass this list to your method, like this:

YourListExpectingMethod(properties);

In the method you'll have to provide some logic to determine to which type to cast the object!

More reading:

  • Object Initializers
    • Object and Collection Initializers
    • How to: Initialize Objects by Using an Object Initializer
  • Casting
    • Casting and Type Conversions
    • How to: Safely Cast by Using as and is Operators
    • Direct casting vs 'as' operator?

Converting brush[] to string or brush[] to color[] to string

Try to use that

        xml.WriteStartElement("cor_frmlocal");
for (int i = 0; i < cor_local.Length; i++)
{
xml.WriteElementString("Cor_local", ((SolidBrush)cor_local[i]).Color.ToArgb().ToString());
}
xml.WriteEndElement();

the problem was in usage of base Brush class object references that do not contain Color property. To handle that you must cast it back to SolidBrush.

To convert brush back

1) create the list of brushes var brushList = new List<Brush>();

2) read color value as var colorValue = Convert.ToInt32(reader.ReadElementString());

3) create color from that value var color = Color.FromArgb(colorValue);

4) create new brush and add it to list list.Add(new SolidBrush(color));

the result code looks like

XmlTextReader reader = new XmlTextReader(filename);
string node_info = "";
var brushList = new List<Brush>();

while(reader.Read())
{
node_info = reader.Name;

if (node_info == "cor_frmlocal")
{
var colorValue = Convert.ToInt32(reader.ReadElementString());
var color = Color.FromArgb(colorValue);
list.Add(new SolidBrush(color));
}
}


Related Topics



Leave a reply



Submit