• 将十六进制色值转换成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别人发来的色值字符串.长度竟然会比正常的多一位。

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

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

  • 相关阅读:
    -_-#【缓存】Content-Type 错误
    ♫【事件】事件处理程序
    -_-#【Node】Express 400 Error: ENOENT, open
    【JS】定位
    【JS】壹零零壹
    洛谷—— P1018 乘积最大
    洛谷—— P1017 进制转换
    洛谷——P1011 车站
    洛谷——P2241 统计方形(数据加强版)
    洛谷——P1548 棋盘问题
  • 原文地址:https://www.cnblogs.com/yffswyf/p/4179980.html
Copyright © 2020-2023  润新知