uwp string to color
This file contains 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 SolidColorBrush GetSolidColorBrush(string hex) | |
{ | |
hex = hex.Replace("#", string.Empty); | |
//#FFDFD991 | |
//#DFD991 | |
//#FD92 | |
//#DAC | |
bool existAlpha = hex.Length == 8 || hex.Length == 4; | |
bool isDoubleHex = hex.Length == 8 || hex.Length == 6; | |
if (!existAlpha && hex.Length != 6 && hex.Length != 3) | |
{ | |
throw new ArgumentException("Input string is invalid color"); | |
} | |
int n = 0; | |
byte a; | |
int hexCount = isDoubleHex ? 2 : 1; | |
if (existAlpha) | |
{ | |
n = hexCount; | |
a = (byte) ConvertHexToByte(hex, 0, hexCount); | |
if (!isDoubleHex) | |
{ | |
a = (byte) (a * 16 + a); | |
} | |
} | |
else | |
{ | |
a = 0xFF; | |
} | |
var r = (byte) ConvertHexToByte(hex, n, hexCount); | |
var g = (byte) ConvertHexToByte(hex, n + hexCount, hexCount); | |
var b = (byte) ConvertHexToByte(hex, n + 2 * hexCount, hexCount); | |
if (!isDoubleHex) | |
{ | |
//#FD92 = #FFDD9922 | |
r = (byte) (r * 16 + r); | |
g = (byte) (g * 16 + g); | |
b = (byte) (b * 16 + b); | |
} | |
return new SolidColorBrush(Windows.UI.Color.FromArgb(a, r, g, b)); | |
} | |
private static uint ConvertHexToByte(string hex, int n, int count = 2) | |
{ | |
return Convert.ToUInt32(hex.Substring(n, count), 16); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment