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);
        }

 

  

posted @ 2014-10-30 18:55  心梦缘  阅读(2276)  评论(0编辑  收藏  举报