Coming soon!

Getting your Windows.UI.Color from a HEX string

In my previous post I talked about how you could style the UWP status bar. Then I stumbled upon the fact that I like using hex colors. So here is my extension method which I use to get my Windows.UI.Color, feel free to use it as well! public

  • c#

By Joris Brauns · 2/17/2016 10:29:44 AM (Original Post)

In my previous post I talked about how you could style the UWP status bar.
Then I stumbled upon the fact that I like using hex colors.

So here is my extension method which I use to get my Windows.UI.Color, feel free to use it as well!

public static Color GetColorFromHex(this string hexString)
{

        if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
            throw new ArgumentException();

        //remove the # at the front
        hexString = hexString.Replace("#", "");

        byte a = 255;
        byte r = 255;
        byte g = 255;
        byte b = 255;

        int start = 0;

        //handle ARGB strings (8 characters long)
        if (hexString.Length == 8)
        {
            a = byte.Parse(hexString.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
            start = 2;
        }

        //convert RGB characters to bytes
        r = byte.Parse(hexString.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
        g = byte.Parse(hexString.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
        b = byte.Parse(hexString.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);

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

That's it, you can start using it as follow:
"#F7A30A".GetColorFromHex();


  • c#

By Joris Brauns · 2/17/2016 10:29:44 AM (Original Post)

Share this blogpost

Looking for talent?

Fill in the form below and we’ll get back to you as soon as possible.

Oops. You seem to have written your full name in invisible ink. Please enter it so we can read it. Oops. You seem to have written your company in invisible ink. Please enter it so we can read it. It seems your e-mail doesn’t exist. Please enter a real one so we can contact you. Oops. You seem to have written your telephone in invisible ink. Please enter it so we can read it.