Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpliest way to convert a Color as a string like #XXXXXX to System.Windows.Media.Brush

Tags:

c#

colors

brush

I think that the title is clear !

What I have now is :

System.Drawing.Color uiui = System.Drawing.ColorTranslator.FromHtml(myString);
var intColor = (uint)((uiui.A << 24) | (uiui.R << 16) | (uiui.G << 8) | (uiui.B << 0));
var bytes = BitConverter.GetBytes(uint.Parse(value));
var brush = new SolidColorBrush();
brush.Color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);

1- myString is like #FFFFFF like I said in the title

2- This fails on the BitConverter.GetBytes line which surprises me cause I got the int representation on my Color !

3- Anyway, I know that COlor conversion are not that intuitive but I feel like I'm not doing it right... Is that the good way ?

like image 827
Guillaume Slashy Avatar asked Feb 07 '12 15:02

Guillaume Slashy


1 Answers

You can use the System.Windows.Media.ColorConverter

var color = (Color)ColorConverter.ConvertFromString("#FF010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("#010203");
//OR
var color = (Color)ColorConverter.ConvertFromString("Red");

//and then:
var brush = new SolidColorBrush(color);  

It's pretty flexible as to what it accepts. Have a look at the examples in XAML here. You can pass any of those string formats in.

Note: These are all in System.Windows.Media (for WPF) not to be confused with System.Drawing (for WinForms)

like image 128
Ray Avatar answered Oct 05 '22 22:10

Ray