zoukankan      html  css  js  c++  java
  • WPF:将HTML RGB颜色值转化为Color对象的两种方式

     (1)方式一:

     Color color1 = (Color)System.Windows.Media.ColorConverter.ConvertFromString("#E0E0E0");
    

    (2)方式二:

    Color color2 = ConvertToColor("#E0E0E0");
    

      

    public static System.Windows.Media.Color ConvertToColor(string value)
    {
           int r = 0, g = 0, b = 0;
           if (value.StartsWith("#"))
           {
                int v = Convert.ToInt32(value.Substring(1), 16);
                r = (v >> 16) & 255; g = (v >> 8) & 255; b = v & 255;
           }
    
           return System.Windows.Media.Color.FromRgb(Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b));
    }
    记住:如果是将RGB(128,24,34)转换为十六进制,可以分别将数字转换为十六进制:
            public string toHex(int digit)
            {
                string hexDigit = digit.ToString("X");
                if (hexDigit.Length == 1)
                {
                    hexDigit = "0" + hexDigit;
                }
                return hexDigit;
            }
    

      然后拼接得到十六进制:

    string colorCode = "#" +toHex(Color.R) +toHex(Color.G) +toHex(Color.B);
    

      

    (3)方法三

            private static Color CreateColorFromString(string s)
            {
                if (string.Compare(s, "None") == 0)
                {
                    return Colors.Transparent;
                }
                s = s.Replace("#", "");
                byte result = 0;
                byte num2 = 0;
                byte num3 = 0;
                byte num4 = 0;
                byte.TryParse(s.Substring(0, 2), NumberStyles.HexNumber, (IFormatProvider)null, out result);
                byte.TryParse(s.Substring(2, 2), NumberStyles.HexNumber, (IFormatProvider)null, out num2);
                byte.TryParse(s.Substring(4, 2), NumberStyles.HexNumber, (IFormatProvider)null, out num3);
                byte.TryParse(s.Substring(6, 2), NumberStyles.HexNumber, (IFormatProvider)null, out num4);
                return System.Windows.Media.Color.FromArgb(result, num2, num3, num4);
            }

      

  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/wangnmhb/p/4063442.html
Copyright © 2011-2022 走看看