Skip to content

Instantly share code, notes, and snippets.

@WillzZz
Last active April 24, 2016 21:54
Show Gist options
  • Select an option

  • Save WillzZz/c728f82ee3fc0bbc551a32b1fd1f423d to your computer and use it in GitHub Desktop.

Select an option

Save WillzZz/c728f82ee3fc0bbc551a32b1fd1f423d to your computer and use it in GitHub Desktop.
Unity3D Hex color helper
using UnityEngine;
public static class Colors
{
/// <summary>
/// Return a UnityEngine.Color from a 32b hex uint
/// </summary>
/// <param name="hex">ex: 00FF00FF </param>
/// <returns>ex Color.green (0f,1f,0f,1f)</returns>
public static Color HexToColor(uint hex)
{
uint red = ExtractRed(hex);
uint green = ExtractGreen(hex);
uint blue = ExtractBlue(hex);
uint alpha = ExtractAlpha(hex);
return new Color(HexToColorFloat(red), HexToColorFloat(green), HexToColorFloat(blue), HexToColorFloat(alpha));
}
/// <param name="color">Hex code for a single 8bit color (0xFF == 1.0f)</param>
/// <returns>Float value from 0 ->1 (0->255)</returns>
public static float HexToColorFloat(uint color)
{
return (int) color / 255f;
}
public static uint ExtractRed(uint color)
{
return (( color >> 24 ) & 0xFF);
}
public static uint ExtractGreen(uint color)
{
return (( color >> 16 ) & 0xFF);
}
public static uint ExtractBlue(uint color)
{
return (( color >> 8 ) & 0xFF);
}
public static uint ExtractAlpha(uint color)
{
return ( color & 0xFF );
}
/// <summary>
/// Convert seperate uint values to a hex color value
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
/// <param name="alpha"></param>
/// <returns></returns>
public static uint CombineRGBA(uint red, uint green, uint blue, uint alpha)
{
return (red << 24) | ( green << 16 ) | ( blue << 8 ) | alpha;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment