1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
public static Color? HexToColor(this string hex)
{
if (hex.IsNullOrEmpty() || !hex.IsHexcode())
return null;
int red, green, blue = 0;
try
{
if (hex.Length == 3)
{
red = int.Parse(hex.Substring(0, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
green = int.Parse(hex.Substring(1, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
blue = int.Parse(hex.Substring(2, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
}
else if (hex.Length == 6)
{
red = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
green = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
blue = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
}
else
return null;
}
catch
{
return null;
}
if (red < 0 || red > 255)
return null;
if (green < 0 || green > 255)
return null;
if (blue < 0 || blue > 255)
return null;
return Color.FromArgb(red, green, blue);
}
public static string ColorToHex(this Color clr)
{
int red = clr.R;
int green = clr.G;
int blue = clr.B;
string colorHex = "#";
colorHex += String.Format("{0:X02}", red);
colorHex += String.Format("{0:X02}", green);
colorHex += String.Format("{0:X02}", blue);
return colorHex;
}
|