Monday, December 17, 2012
Parsing a Hex Color value
Websites and applications can store a color in a various number of ways. Some of the most commons ways found on the web are:
- RGB Hex values
- Abreviated RGB Hex values
- A string that is meant to be mapped to standard color values, such as "Blue".
private bool tryParseHex(string hexString, out Byte hexByte) { return Byte.TryParse( hexString, System.Globalization.NumberStyles.AllowHexSpecifier, null, out hexByte); }This calling function can be customized to handle the hex formats you expect. The function below handles "#FFFFFF" and "FFFFFF". If it doesn't match that format, or isn't valid hex, it calls another function to map the string value to a standard color.
private SolidColorBrush buildColumnHeaderColor(string color) { //Use hex value if passed if (color.StartsWith("#")) color = color.Substring(1); Byte red, green, blue; if (color.Length == 6 && tryParseHex(color.Substring(0, 2), out red) && tryParseHex(color.Substring(2, 2), out green) && tryParseHex(color.Substring(4, 2), out blue)) { return new SolidColorBrush(Color.FromArgb(255, red, green, blue)); } //if no hex value, map to colors in Assets/Styles.xaml else { return mapStandardColor(color); } }
Labels: Color parsing, TryParse hex
Subscribe to Posts [Atom]