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:
  1. RGB Hex values
  2. Abreviated RGB Hex values
  3. A string that is meant to be mapped to standard color values, such as "Blue".
What if we want an application to be able to handle any of these three? The 3rd case would require figuring out what those standard colors are and doing a Switch construct. The other two are similar and require building Byte values out of the string value. Since we don't know if the string contains any hex we should utilize a TryParse function. Using a TryParse to read in a hex value can be a bit tricky, as shown here http://stackoverflow.com/questions/4279892/convert-a-string-containing-a-hexadecimal-value-starting-with-0x-to-an-integer. So I've broken it out into it's own function:
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: ,


This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]