How to generate random color names in C#

2019-01-08 08:33发布

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# random colors
14条回答
\"骚年 ilove
2楼-- · 2019-01-08 09:10

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;
}
查看更多
太酷不给撩
3楼-- · 2019-01-08 09:10

generate a random number and cast it to KnownColor Type

((KnownColor)Random.Next());
查看更多
萌系小妹纸
4楼-- · 2019-01-08 09:11

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.

查看更多
放我归山
5楼-- · 2019-01-08 09:16
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;
        }
查看更多
一夜七次
6楼-- · 2019-01-08 09:18

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

查看更多
▲ chillily
7楼-- · 2019-01-08 09:18

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.

查看更多
登录 后发表回答