Toolroom Tech Blog

Devlopers Digest

Hex string to Color conversion on Windows Phone 7.x

Function to convert a hex string to a Color

In a Windows Phone 7 project I recently needed a function that does the work of System.Drawing.ColorTranslator.FromHtml(string color). Therefore I wrote this little extension method.

It deals with RGB and ARGB input values, with or without the leading hash.

public static Color FromHtml(this string s)
{
	// Check fore a valid code (RGB = 6 chars, ARGB = 8 chars)
	var regex = new Regex(@"^[A-Fa-f0-9]*$");
	if (s == null || ((s = s.Trim().TrimStart('#')).Length != 6 && s.Length != 8) || !regex.IsMatch(s))
		return Colors.White;

	int index = 0;

	// If the color length is 8, the first 2 chars contain the alpha part
	byte a = 255;
	if (s.Length == 8) 
	{
		a = Convert.ToByte(s.Substring(0, 2), 16);
		index += 2;
	}

	// Get R value
	byte r = Convert.ToByte(s.Substring(index, 2), 16);
	index += 2;
	// Get G value
	byte g = Convert.ToByte(s.Substring(index, 2), 16);
	index += 2;
	// Get B value
	byte b = Convert.ToByte(s.Substring(index, 2), 16);

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

Usage:

var color1 = "#CC3333".FromHtml();

var color2 = "CC3333".FromHtml();

var color3 = "#FFCC3333".FromHtml();
Loading