将十六进制色值转换成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