Converting a text string to a Brushes Color object in C#

We want to dynamically go from a list of Colors (ie, Red, Yellow, White) to the Brush object types shown in my previous article: Adding Text to Images with C# .Net Bitmap objects – We’ll show a few solutions for mapping strings to Brush Color objects.

Try this one first. Simply map your string to a Color using the FromName function like this:

Color yellowColor = Color.FromName("Yellow");

Alternatively, you can use a ColorConverter like this:

TypeConverter typeConverter1 = TypeDescriptor.GetConverter(typeof(Color));
TypeConverter typeConverter2 = new ColorConverter();
Color yellowColor2 = (Color)tc.ConvertFromString("Yellow");

Lastly, you can use Reflection on Color or Brush like this:

Color yellowColor3 = (Color)typeof(Color).GetProperty("Yellow").GetValue(null, null);

Leave a Reply

Your email address will not be published. Required fields are marked *