代码改变世界

颜色转化的两种方法

2013-07-16 07:20  dongyanlei  阅读(228)  评论(0编辑  收藏  举报
颜色值转化的两种方法

        public Color ReturnColorFromString(string color)
        {
            string alpha, red, green, blue;
            if (color.Length == 7)
            {
                alpha = "ff";
                red = color.Substring(1, 2);
                green = color.Substring(3, 2);
                blue = color.Substring(5, 2);

            }
            else
            {
                alpha = color.Substring(1, 2);
                red = color.Substring(3, 2);
                green = color.Substring(5, 2);
                blue = color.Substring(7, 2);
            }
            byte alphaByte = Convert.ToByte(alpha, 16);
            byte redByte = Convert.ToByte(red, 16);
            byte greenByte = Convert.ToByte(green, 16);
            byte blueByte = Convert.ToByte(blue, 16);
            return Color.FromArgb(alphaByte, redByte, greenByte, blueByte);
        } 


        /// <summary>
        /// 从颜色代码转换为RGB
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        private Color getColorFromCode(string htmlColr)
        {
            int baseIndex = 1;
            byte a, r, g, b;
            a = r = g = b = 255;
            if (htmlColr.Length == 9)
            {
                a = Convert.ToByte(htmlColr.Substring(baseIndex, 2), 16);
                baseIndex += 2;
            }
            r = Convert.ToByte(htmlColr.Substring(baseIndex, 2), 16);
            g = Convert.ToByte(htmlColr.Substring(baseIndex += 2, 2), 16);
            b = Convert.ToByte(htmlColr.Substring(baseIndex += 2, 2), 16);
            return Color.FromArgb(a, r, g, b);
        }
View Code