Convert Hex (int) to Color/Color32?

Hey, I need to get better formula for converting Hex as integer to Color or Color32 form in Unity. Can someone give me a hint?

asking for a better formula implies that you've already tried something. posting that code may help to guide you...

5 Answers

5

Using a modified version of this: http://wiki.unity3d.com/index.php?title=HexConverter
Here is what I have been using:

    // Note that Color32 and Color implictly convert to each other. You may pass a Color object to this method without first casting it.
	public static string colorToHex(Color32 color)
	{
		string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");
		return hex;
	}
	
	public static Color hexToColor(string hex)
	{
		hex = hex.Replace ("0x", "");//in case the string is formatted 0xFFFFFF
		hex = hex.Replace ("#", "");//in case the string is formatted #FFFFFF
		byte a = 255;//assume fully visible unless specified in hex
		byte r = byte.Parse(hex.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
		byte g = byte.Parse(hex.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
		byte b = byte.Parse(hex.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
		//Only use alpha if the string has enough characters
		if(hex.Length == 8){
			a = byte.Parse(hex.Substring(6,2), System.Globalization.NumberStyles.HexNumber);
		}
		return new Color32(r,g,b,a);
	}

Thank you Taylor, this helped me!

This is very similar to what I use. You may want to be careful with your Alpha value - what you want to parse starts at 6, not 4.

Awesome function, I'd just like to point out one tiny typo: a = byte.Parse(hex.Substring(6,2), System.Globalization.NumberStyles.HexNumber);

Threw this one in my utility class right away, thank you :)

Thanks ghost and Snownova for catching my mistake! I have updated the post.

looked for hex to rgb on google forums. unity uses rgba color.
try this page…

You can use some bitwise operations like this:

public Color32 ToColor(int HexVal)
{
    byte R = (byte)((HexVal >> 16) & 0xFF);
    byte G = (byte)((HexVal >> 8) & 0xFF);
    byte B = (byte)((HexVal) & 0xFF);
    return new Color32(R, G, B, 255);
}

As this is the first link that pops up, I thought I can provide much easier answer.

Unity has a built-in Utility for this:

Classy extension method on Color

   public static string ToHex(this Color color)
    {
        Color32 c = color;
        var hex = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", c.r, c.g, c.b, c.a);
        return hex;
    }