Ana*_*bhi 2 c# windows-phone-8
我想在我的Windows 8移动应用程序中从Web颜色值设置边框背景颜色.
我找到了一种方法将十六进制转换为Argb,但它不适用于我..
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));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用上面的方法..
Border borderCell = new Border();
var col = FromHex("#DD4AA3");
var color =new System.Windows.Media.SolidColorBrush(col);
borderCell.Background = color;
Run Code Online (Sandbox Code Playgroud)
但是,如果我传递颜色十六进制值如下
var col = FromHex("#FFEEDDCC");
Run Code Online (Sandbox Code Playgroud)
它的工作正常,但它不适用于我的十六进制颜色值.
在发布这个问题之前,我通过这个堆栈答案. 如何使用.NET从十六进制颜色代码中获取颜色?
为什么不简单地使用System.Windows.Media.ColorConverter?
Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#EA1515");
Run Code Online (Sandbox Code Playgroud)
最后我发现了一个从十六进制字符串返回颜色的方法
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5306 次 |
| 最近记录: |