将十六进制色值转换成Color

在给Background赋值时,除了自带的Red,Blue,Black等,可以通过以下方法赋予其他颜色。

主要是将Hex转换成ARGB(A:alpha,表示透明度、R:Red、G:Green、B:Blue),其中ARGB取值均在0--255之间 

该方法传入的字符串参数可以类似 #21459A 或者 #FF21459A

public static Color? GetColorFromHex(String colorStr)  //? 表示返回值可以为null                                      { if (colorStr != null && (colorStr.Length == 7 || colorStr.Length == 9)) { byte a = 255; int posi = 1; if (colorStr.Length == 9) { a = Byte.Parse(colorStr.Substring(posi, 2), NumberStyles.HexNumber); posi += 2; } byte r = Byte.Parse(colorStr.Substring(posi, 2), NumberStyles.HexNumber); posi += 2; byte g = Byte.Parse(colorStr.Substring(posi, 2), NumberStyles.HexNumber); posi += 2; byte b = Byte.Parse(colorStr.Substring(posi, 2), NumberStyles.HexNumber); return Color.FromArgb(a, r, g, b); } return null; }

之后给背景色赋值

 grid.Background= new SolidColorBrush(GetColorFromHex("#21459A").Value);

当然在知道RGB的时候也可以采取如下方式:

 grid.Background = new SolidColorBrush() { Color = Color.FromArgb(255,33, 69, 154) };
             
//this.Foreground = new SolidColorBrush(Color.FromArgb(255,33, 69, 154) );    //未创建对象  这种方法不行


PS: 在编程过程中,复制Win8.1上的Skype别人发来的色值字符串.长度竟然会比正常的多一位。

(原因是在末尾会有一个为“”的东西。。。的确为空,但是用键盘方向键就可以观察到里面是有东西的)

且能够提取到这个为空的字符。也因为这个小细节苦恼了好久。。‏

转载于:https://www.cnblogs.com/yffswyf/p/4179980.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值