Archive

Posts Tagged ‘Convert hex string to Color’

Silverlight for Windows Phone 7: How to get color from hex string

June 9th, 2011 No comments

     In my Silverlight Windows Phone 7 application I actively use HTML color codes, that are hexadecimal strings representing components of red, green and blue colors. Additionally, such hex-string can contains alpha channel value. For example, #FF0080 (Light Purple). To convert hex-strings to Color I have developed the following method:

protected static Color GetColorFromHexString(string s)
{ 
    // remove artifacts
    s = s.Trim().TrimStart('#');

    // only 8 (with alpha channel) or 6 symbols are allowed
    if(s.Length != 8 && s.Length != 6)
        throw new ArgumentException("Unknown string format!");

    int  startParseIndex    = 0;
    bool alphaChannelExists = s.Length == 8; // check if alpha canal exists            

    // read alpha channel value
    byte a = 255;
    if(alphaChannelExists)
    {
        a = System.Convert.ToByte(s.Substring(0, 2), 16);
        startParseIndex += 2;
    }

    // read r value
    byte r = System.Convert.ToByte(s.Substring(startParseIndex, 2), 16);
    startParseIndex += 2;
    // read g value
    byte g = System.Convert.ToByte(s.Substring(startParseIndex, 2), 16);
    startParseIndex += 2;
    // read b value
    byte b = System.Convert.ToByte(s.Substring(startParseIndex, 2), 16);

    return Color.FromArgb(a, r, g, b);
}

I Hope this helps someone!

Related posts: