Skip to content

Instantly share code, notes, and snippets.

@matrostik
Created January 25, 2017 10:48
Show Gist options
  • Save matrostik/ba5836ac4465b65a8ed847bc77c92d61 to your computer and use it in GitHub Desktop.
Save matrostik/ba5836ac4465b65a8ed847bc77c92d61 to your computer and use it in GitHub Desktop.
HexToColorConverter
public static class HexToColorConverter
{
/// <summary>
/// Converts a hexadecimal string value into a Brush.
/// </summary>
public static SolidColorBrush ConvertToBrush(string value)
{
return new SolidColorBrush(ConvertToColor(value));
}
/// <summary>
/// Converts a hexadecimal string value into a Color.
/// </summary>
public static Color ConvertToColor(string value)
{
if (string.IsNullOrEmpty(value))
{
return Colors.Black;
}
byte alpha;
byte pos = 0;
var hex = value.Replace("#", "");
if (hex.Length == 8)
{
alpha = Convert.ToByte(hex.Substring(pos, 2), 16);
pos = 2;
}
else
{
alpha = Convert.ToByte("ff", 16);
}
var red = Convert.ToByte(hex.Substring(pos, 2), 16);
pos += 2;
var green = Convert.ToByte(hex.Substring(pos, 2), 16);
pos += 2;
var blue = Convert.ToByte(hex.Substring(pos, 2), 16);
return Color.FromArgb(alpha, red, green, blue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment