Created
January 25, 2017 10:48
-
-
Save matrostik/ba5836ac4465b65a8ed847bc77c92d61 to your computer and use it in GitHub Desktop.
HexToColorConverter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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