How to generate random color names in C#

C#RandomColors

C# Problem Overview


I need to generate random color names e.g. "Red", "White" etc. How can I do it? I am able to generate random color like this:

Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255), randonGen.Next(255), 
randonGen.Next(255));

but I need the names and not all colors generated like this have a known name.

Thanks

C# Solutions


Solution 1 - C#

Use Enum.GetValue to retrieve the values of the KnownColor enumeration and get a random value:

Random randomGen = new Random();
KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
KnownColor randomColorName = names[randomGen.Next(names.Length)];
Color randomColor = Color.FromKnownColor(randomColorName);

Solution 2 - C#

Take a random value and get from KnownColor enum.

May be by this way:

System.Array colorsArray = Enum.GetValues(typeof(KnownColor));
KnownColor[] allColors = new KnownColor[colorsArray.Length];

Array.Copy(colorsArray, allColors, colorsArray.Length);
// get a randon position from the allColors and print its name.

Solution 3 - C#

Ignore the fact that you're after colors - you really just want a list of possible values, and then take a random value from that list.

The only tricky bit then is working out which set of colors you're after. As Pih mentioned, there's KnownColor - or you could find out all the public static properties of type Color within the Color structure, and get their names. It depends on what you're trying to do.

Note that randomness itself can be a little bit awkward - if you're selecting multiple random colors, you probably want to use a single instance of Random`. Unfortunately it's not thread-safe, which makes things potentially even more complicated. See my article on randomness for more information.

Solution 4 - C#

Sounds like you just need a random color from the KnownColor enumeration.

Solution 5 - C#

Or you could try out this: For .NET 4.5

public Windows.UI.Color GetRandomColor()
{
            Random randonGen = new Random();
            Windows.UI.Color randomColor = 
                Windows.UI.Color.FromArgb(
                (byte)randonGen.Next(255), 
                (byte)randonGen.Next(255),
                (byte)randonGen.Next(255), 
                (byte)randonGen.Next(255));
            return randomColor;
}

Solution 6 - C#

Put the colors into an array and then choose a random index:

class RandomColorSelector
{
    static readonly Color[] Colors = 
        typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static)
       .Select(propInfo => propInfo.GetValue(null, null))
       .Cast<Color>()
       .ToArray();

    static readonly string[] ColorNames =  
        typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static)
        .Select(propInfo => propInfo.Name)
        .ToArray();
    
    private Random rand = new Random();

    static void Main(string[] args)
    {
        var colorSelector = new RandomColorSelector();
        var color = colorSelector.GetRandomColor();

        // in case you are only after the *name*
        var colorName = colorSelector.GetRandomColorName();            
    }

    public Color GetRandomColor()
    {
        return Colors[rand.Next(0, Colors.Length)];
    }

    public string GetRandomColorName()
    {
        return ColorNames[rand.Next(0, Colors.Length)];
    }
}

Note that the sample above simply looks up all static properties of the Color type. You might want to improve this by checking that the actual return type of the property is a Color.

Solution 7 - C#

Copied code from Retrieve a list of colors in C#

CODE:

private List<string> GetColors()
{
    //create a generic list of strings
    List<string> colors = new List<string>();
    //get the color names from the Known color enum
    string[] colorNames = Enum.GetNames(typeof(KnownColor));
    //iterate thru each string in the colorNames array
    foreach (string colorName in colorNames)
    {
        //cast the colorName into a KnownColor
        KnownColor knownColor = (KnownColor)Enum.Parse(typeof(KnownColor), colorName);
        //check if the knownColor variable is a System color
        if (knownColor > KnownColor.Transparent)
        {
            //add it to our list
            colors.Add(colorName);
        }
    }
    //return the color list
    return colors;
}

Solution 8 - C#

I would build a lookup table. Especially since some colors are up to personal interpretation.

Go through each color value in the Color struct ( http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx ) and map it to the RGB values. Then to convert back, lookup the RGB value to see if it has a named color.

Solution 9 - C#

I combined some of the answers in this thread and came up with more generic solution for generating a random KnownColor:

public class Enum<T> where T : struct, Enum
{
    public static T Random
    {
        get => GetRandom();
    }

    public static T SeededRandom(int seed)
    {
        return GetRandom(seed);
    }

    private static T GetRandom(int? seed = null)
    {
        var enumValues = Enum.GetValues<T>();
        Random r;
        if(seed.HasValue)
        {
            r = new Random(seed.Value);
        }
        else
        {
            r = new Random();
        }
        var randomIndex = r.Next(enumValues.Length - 1);
        return enumValues[randomIndex];
    }

}

Then you can use this as:

public Color GetRandomColor()
{
    var randomKnownColor = Enum<KnownColor>.Random;
    return Color.FromKnownColor(randomKnownColor);
}

You can also use the SeededRandom(int seed) method which was more suited for my use-case. Where I wanted to assign a random color based on some Id and get the same color for the same Id when the process is repeated.

Works on C# >= 7.3

Solution 10 - C#

There is no way to Randomize an Enumeration, as you want to do, the most suitable solution would pass by setting a List with all the values of the colors, then obtain an integer randomizing it and use it as the index of the list.

Solution 11 - C#

private string getRandColor()
        {
            Random rnd = new Random();
            string hexOutput = String.Format("{0:X}", rnd.Next(0, 0xFFFFFF));
            while (hexOutput.Length < 6)
                hexOutput = "0" + hexOutput;
            return "#" + hexOutput;
        }

Solution 12 - C#

Here, I'm generating colors based on profile completed.

public string generateColour(Decimal percentProfileComplete )
{
    if(percent < 50)
    { 
        return "#" + (0xff0000 | Convert.ToInt32(Convert.ToDouble(percentProfileComplete ) * 5.1) * 256).ToString("X6");
    }
    return "#" + (0xff00 | (255 - Convert.ToInt32((Convert.ToDouble(percentProfileComplete ) - 50) * 5.1)) * 256 * 256).ToString("X6");
}

Solution 13 - C#

I would have commented on Pih's answer; however, not enough karma. Anywho, I tried implementing this and ran into the issue of the same color being generated from multiple calls as the code was called repeatedly in quick succession (i.e. the randomGen was the same and since it is based on the clock = same results ensued).

Try this instead:

public class cExample
{
    ...
    Random randomGen = new Random();
    KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
    ...
    private Color get_random_color()
    {
         KnownColor randomColorName = names[randomGen.Next(names.Length)];
         return Color.FromKnownColor(randomColorName);
    }
    ...
}

Solution 14 - C#

To clear up the syntax errors in the original question, it's

Color.FromRgb, and

(Byte)random2.Next(255)

converts the integer to a byte value needed by Color:

    Random random2 = new Random();
    public int nn = 0x128;
    public int ff = 0x512;
    Color randomColor = Color.FromRgb((Byte)random2.Next(nn, ff), (Byte)random2.Next(nn, ff), (Byte)random2.Next(nn, ff));

Solution 15 - C#

If you wanted to get random color from specific colors list,
then try below one

Color[] colors = new[] { Color.Red, Color.Blue, Color.FromArgb(128, 128, 255) };    //Add your favorite colors list
Random randonGen = new Random();
Color randomColor = colors[Generator.Next(0, colors.Length)];    //It will choose random color from "colors" array

Solution 16 - C#

generate a random number and cast it to KnownColor Type

((KnownColor)Random.Next());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser579674View Question on Stackoverflow
Solution 1 - C#Konrad RudolphView Answer on Stackoverflow
Solution 2 - C#PihView Answer on Stackoverflow
Solution 3 - C#Jon SkeetView Answer on Stackoverflow
Solution 4 - C#DavidView Answer on Stackoverflow
Solution 5 - C#Vivek SauravView Answer on Stackoverflow
Solution 6 - C#Dirk VollmarView Answer on Stackoverflow
Solution 7 - C#Javed AkramView Answer on Stackoverflow
Solution 8 - C#MaxView Answer on Stackoverflow
Solution 9 - C#dominik737View Answer on Stackoverflow
Solution 10 - C#AmedioView Answer on Stackoverflow
Solution 11 - C#jonView Answer on Stackoverflow
Solution 12 - C#T GuptaView Answer on Stackoverflow
Solution 13 - C#S. ArseneauView Answer on Stackoverflow
Solution 14 - C#pollarisView Answer on Stackoverflow
Solution 15 - C#Sorry IwontTellView Answer on Stackoverflow
Solution 16 - C#atoMerzView Answer on Stackoverflow