I code therefore I am.

Posts tagged "conversion"


February 25, 2011 at 1:16pm
Notes
Comments (View)

Tags:
CSharp  conversion  

Hex String to Color (ARGB)

public Color HexStringToColor(string hex)
{
	hex = hex.Replace("#", "").ToLowerInvariant();

	
	if (hex.Length == 6)
	{
		hex = "ff" + hex;
	}
	else if (hex.Length != 8)
	{
		throw new Exception(hex + " 
			is not a valid 6 or 8-place 
			hexadecimal color code.");
	}

	int a, r, g, b;
	a = Convert.ToInt32(hex.Substring(0, 2), 16);
	r = Convert.ToInt32(hex.Substring(2, 2), 16);
	g = Convert.ToInt32(hex.Substring(4, 2), 16);
	b = Convert.ToInt32(hex.Substring(6, 2), 16);

	return Color.FromArgb(a, r, g, b);
}
(this assumes input is correct format - either ‘#FFFFFF’ or ‘FFFFFF’)