Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 1.19 KB

Convert-hex-to-color.md

File metadata and controls

36 lines (29 loc) · 1.19 KB

Convert hex to color

Converts a hexadecimal string representation of a color to its Windows.UI.Color ARGB (alpha, red, green, blue) equivalent or vice-versa.

using System;
using System.Globalization;
using Windows.UI;

public static Color ConvertHexToColor(string hex)
{
    hex = hex.Remove(0, 1);
    byte a = hex.Length == 8 ? Byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber) : (byte)255; 
    byte r = Byte.Parse(hex.Substring(hex.Length - 6, 2), NumberStyles.HexNumber);
    byte g = Byte.Parse(hex.Substring(hex.Length - 4, 2), NumberStyles.HexNumber);
    byte b = Byte.Parse(hex.Substring(hex.Length - 2), NumberStyles.HexNumber);
    return Color.FromArgb(a, r, g, b);
}

public static string ConvertColorToHex(Color color)
{
    return $"#{color.A}{color.R}{color.G}{color.B}"; 
}

See also

Color sructure
ARGB
Interpolated strings (strings with a $ prefix)
?: operator