Web users like to use a hexadecimal string to identify the color, such as "# f5f5f5". Naturally, this is represented by argb in Silverlight/WPF: "# fff5f5f5" (the first two identities are alpha, that is, transparency ). There is no problem in XAML, but what if we want to set the color in the code or read the relevant values from XML?
It is inevitable that an error will be reported. At least I don't know whether SL or WPF has published this converter. I can't do anything about it anyway.
Here is a code snippet that helps us convert a hexadecimal string into an argb color.
Double-click all code
1234567891011 |
public static Color ToColor( this string colorName) { if (colorName.StartsWith( "#" )) colorName = colorName.Replace( "#" , string .Empty); int v = int .Parse(colorName, System.Globalization.NumberStyles.HexNumber); return new Color() { A = Convert.ToByte((v >> 24) & 255), R = Convert.ToByte((v >> 16) & 255), G = Convert.ToByte((v >> 8) & 255), B = Convert.ToByte((v >> 0) & 255) }; } |
Here I made the extension method, and then used it like this
Double-click all code
12 |
Rectangle rectangle = new Rectangle(); rectangle.Fill = new SolidColorBrush( "#FFF5F5F5" .ToColor()); |
Naturally, no problem.
Color to int32
Here you may ask, what is the use of color to int? In fact, if you use some existing image libraries, they often express color as an int value. In this case, the argb value is represented by a 32-bit int in the order of its bytes rggbb. Here we can perform the following conversions:
Double-click all code
1234567 |
public static int ToArgb( this Color color) { int argb = color.A << 24; argb += color.R << 16; argb += color.G << 8; argb += color.B; return argb; } |
The following is a comprehensive application of the two methods:
Double-click all code
12345 |
Rectangle rectangle = new Rectangle(); SolidColorBrush scb = new SolidColorBrush(); scb.Color = "#FFF5F5F5" .ToColor(); rectangle.Fill = scb; MessageBox.Show(scb.Color.ToArgb().ToString()); |
Guess what the value of MessageBox show is?
OK, meeting :)