Game Development Community

Convert Hex to Color and back

by Jonathon Stevens · in Torque X 2D · 04/08/2007 (8:16 pm) · 2 replies

Here is some code for converting hex to color and visa versa (also hex to int and vica versa)

public static Color HexToColor(String hexString)
        {
            Color actColor;
            int redCode = 0;
            int greenCode = 0;
            int blueCode = 0;

            if (hexString.StartsWith("#") && hexString.Length == 7)
            {
                redCode = HexToInt(hexString.Substring(1, 2));
                greenCode = HexToInt(hexString.Substring(3, 2));
                blueCode = HexToInt(hexString.Substring(5, 2));

                actColor = new Color((byte)redCode, (byte)greenCode, (byte)blueCode);
            }
            else
                actColor = Color.White;

            return actColor;
        }


        public static String ColorToHex(Color actColor)
        {
            return "#" + IntToHex(actColor.R) + IntToHex(actColor.G) + IntToHex(actColor.B);
        }

        public static string IntToHex(int number)
        {
            return String.Format("{0:x}", number);
        }

        public static int HexToInt(string hexString)
        {
            return int.Parse(hexString, System.Globalization.NumberStyles.HexNumber, null);
        }


www.linkedin.com/img/webpromo/btn_viewmy_160x25.gif

www.mmogamedev.info/images/imgdc_ad1.gif

About the author

With a few casual games under his belt as CEO of Last Straw Productions, Jonathon created the increasingly popular Indie MMO Game Developers Conference.


#1
04/08/2007 (9:44 pm)
I havent gone that far in browsing functionality of TX yet, but could you inform me on how this function is useful?

Thanks,

-Jason
#2
04/09/2007 (6:12 am)
This is useful if you have a hex value for a color and want to use that to set the color of text or whatever. .net uses the 'color' namespace which takes color names. This converts hex to the color names that .net supports and back again.

www.linkedin.com/img/webpromo/btn_viewmy_160x25.gif

www.mmogamedev.info/images/imgdc_ad1.gif