Skip to content

Instantly share code, notes, and snippets.

@LambdaSix
Last active December 12, 2015 12:19
Show Gist options
  • Save LambdaSix/4770797 to your computer and use it in GitHub Desktop.
Save LambdaSix/4770797 to your computer and use it in GitHub Desktop.
Convert Long (6/8 hex colour) to a Color struct.
///<Summary>
/// Converts a hexadecimal colour code (8-hex with alpha) into a .net Color struct.
///</Summary>
///<remarks>
/// If the input string is invalid, will throw an exception from parsing, you
/// should handle this in the callee.
///</remarks>
///<param name="colour">The colour in numerical form. Prefix with # for hexadecimal format.</param>
///<example>
/// Example of converting hexadecimal string and ulong values to a Color.
/// <code>
/// var color1 = ConvertToColour("#FFAABBCC");
/// var color2 = ConvertToColour("4289379276");
/// </code>
///</example>
public Color ConvertToColour(string colour)
{
ulong longColour;
if (colour.StartsWith("#"))
{
longColour = UInt64.Parse(colour.TrimStart('#'), NumberStyles.HexNumber);
}
else
{
longColour = UInt64.Parse(colour, NumberStyles.Integer);
}
var bytes = GetBytes(longColour);
return Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]);
}
/// <summary>
/// Return an array of bytes from the passed ulong
/// </summary>
private byte[] GetBytes(ulong value)
{
Byte[] byteArray = new byte[4];
// convert from an unsigned long int to a 4-byte array
byteArray[0] = (byte)((int) ((value >> 24) & 0xFF));
byteArray[1] = (byte)((int) ((value >> 16) & 0xFF));
byteArray[2] = (byte)((int) ((value >> 8) & 0XFF));
byteArray[3] = (byte)((int) ((value & 0XFF)));
return byteArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment