Thursday 7 April 2011

Code behind Color List

Some users have requested the code I used to generate the Any Colur you like as long as its .NET post last week. The following is the c# function I used to extract the list of colours.
void ShowColours()
{
    // Get an array of all known colours
    KnownColor[] colours = (KnownColor[])Enum.GetValues(typeof(KnownColor));
    for (int i = 0; i < colours.Length; i++)
    {
        Color c = Color.FromName(colours[i].ToString());

        if (c.IsSystemColor)
        {
            Console.WriteLine(
                string.Format(
                "System Colour : {0} [Hex #{1}] [RGB {2}/{3}/{4}]",
                    c.Name, c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"),
                    BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.G, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.B, byte.MinValue, }, 0)
                    ));
        }
        else
        {
            Console.WriteLine(
                string.Format(
                "Predefined Colour : {0} [Hex #{1}] [RGB {2}/{3}/{4}]",
                    c.Name, c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"),
                    BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.G, byte.MinValue, }, 0),
                    BitConverter.ToInt16(new byte[2] { c.B, byte.MinValue, }, 0)
                    ));
        }
    }
The following Extracts a list of all System.Drawing.KnownColor Enumeration values and assigns them to an array.
KnownColor[] colours = (KnownColor[])Enum.GetValues(typeof(KnownColor));

The following line converts the byte value for the colour, and converts it to a Hexadecimal value.
c.R.ToString("X2")

Converts a byte value to an Int16 value. The colour is represented by a single byte but the functon requires two bytes, so we add a second byte with value as byte.MinValue. The result is a value 0-255 inclusive representing the colour value.
BitConverter.ToInt16(new byte[2] { c.R, byte.MinValue, }, 0)
Hope this code helps!
Disclaimer: The content provided in this article is not warranted or guaranteed by rnddev. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts. As such it is inferred on to the reader to employ real-world tactics for security and implementation of best practices. I am not liable for any negative consequences that may result from implementing any information covered in this or other articles or blog posts.

No comments:

Post a Comment