How to generate random color names in C#

后端 未结 15 1689
清酒与你
清酒与你 2020-11-29 21:57

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 Ran         


        
相关标签:
15条回答
  • 2020-11-29 23:00

    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.

    0 讨论(0)
  • 2020-11-29 23:00

    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");
    }
    
    0 讨论(0)
  • 2020-11-29 23:01

    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);
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题