User Tools

Site Tools


notes:uwp:colors

Colors in UWP

Below there are a few handly helpers to deal with the Windows.UI.Colors class:

using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
...
private long GetColorValue(Windows.UI.Color col)
{
    return ((long)col.A << 24) | ((long)col.R << 16) | ((long)col.G << 8) | ((long)col.B);
}
 
private long GetColorValue(byte a, byte r, byte g, byte b)
{
    return ((long)a << 24) | ((long)r << 16) | ((long)g << 8) | ((long)b);
}
 
private void GetRgb(long colorValue, out byte a, out byte r, out byte g, out byte b)
{
    a = (byte)((colorValue & 0xFF000000) >> 24);
    r = (byte)((colorValue & 0x00FF0000) >> 16);
    g = (byte)((colorValue & 0x0000FF00) >> 8);
    b = (byte)(colorValue & 0x000000FF);
}
 
private Windows.UI.Color GetColor(long colorValue)
{
    byte a, r, g, b;
    GetRgb(colorValue, out a, out r, out g, out b);
 
    Windows.UI.Color col = new Windows.UI.Color();
    col.A = a;
    col.R = r;
    col.G = g;
    col.B = b;
 
    return col;
}
 
// GetColors obtains a list of colors and their names using reflection.
private List<ColorDefinition> GetColors()
{
    var colors = new List<ColorDefinition>();
 
    // The DeclaredProperties property returns all the properties of the Colors class
    // as PropertyInfo objects. All the properties in the Colors class are static.
    IEnumerable<PropertyInfo> props = typeof(Windows.UI.Colors).GetTypeInfo().DeclaredProperties;
 
    foreach (PropertyInfo prop in props)
    {
        // Obtain the value of a static property 'prop'.
        Windows.UI.Color col = (Windows.UI.Color)prop.GetValue(null);
 
        colors.Add(
          new ColorDefinition { WindowsColor = col, ColorName = prop.Name, ColorValue = GetColorValue(col) });
    }
 
    return colors;
}
 
class ColorDefinition
{
    public Windows.UI.Color WindowsColor { get; set; }
    public string ColorName { get; set; }
    public long ColorValue { get; set; }
 
    public override string ToString()
    {
        return $"{ColorName} = #{ColorValue:X8}";
    }
}

Examples of usage:

Debug.WriteLine(GetColorValue(Windows.UI.Colors.Purple).ToString("X")); // FF800080
Debug.WriteLine(GetColorValue(255, 128, 0, 128).ToString("X")); // FF800080
 
byte a, r, g, b;
GetRgb(GetColorValue(Windows.UI.Colors.Purple), out a, out r, out g, out b);
Debug.WriteLine($"A={a} R={r} G={g} B={b}"); // A=255 R=128 G=0 B=128
 
Windows.UI.Color color = GetColor(0xFF800080);
Debug.WriteLine(color.ToString()); // #FF800080
 
List<ColorDefinition> colors = GetColors();
foreach (ColorDefinition def in colors)
    Debug.WriteLine(def.ToString());
// AliceBlue = #FFF0F8FF
// AntiqueWhite = #FFFAEBD7
// Aqua = #FF00FFFF
// Aquamarine = #FF7FFFD4
// etc.
notes/uwp/colors.txt · Last modified: 2016/11/22 by admin