I want to set Border background color from web color value in my windows 8 mobile application .
I found one method that convert hex to Argb but its not working for me ..
private System.Windows.Media.Color FromHex(string hex)
{
string colorcode = hex;
int argb = Int32.Parse(colorcode.Replace("#", ""), System.Globalization.NumberStyles.HexNumber);
return System.Windows.Media.Color.FromArgb((byte)((argb & -16777216) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
}
I am using above method like..
Border borderCell = new Border();
var col = FromHex("#DD4AA3");
var color =new System.Windows.Media.SolidColorBrush(col);
borderCell.Background = color;
But if I pass color hex value like below
var col = FromHex("#FFEEDDCC");
its works fine but it not work on my hex color value.
Before posting this question I go thru this stack answer. How to get Color from Hexadecimal color code using .NET?
Convert System.Drawing.Color to RGB and Hex Value
Why not simply use System.Windows.Media.ColorConverter
?
Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#EA1515");
finally I found one method that return color from hex string
public System.Windows.Media.Color ConvertStringToColor(String hex)
{
//remove the # at the front
hex = hex.Replace("#", "");
byte a = 255;
byte r = 255;
byte g = 255;
byte b = 255;
int start = 0;
//handle ARGB strings (8 characters long)
if (hex.Length == 8)
{
a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
start = 2;
}
//convert RGB characters to bytes
r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber);
return System.Windows.Media.Color.FromArgb(a, r, g, b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With