开发者

generating a specefied number of random but unique colors

What I am trying to do is give each item in my listView to have a unique color. So what I have is number of items in my list view as 'count'

My approach is to call the method below and give the method number of my items, and then it should have an array which saves the first color, then开发者_JS百科 when next color is going to be generated it should be compared with colors before it in the array.

The problem is I cant figure out a way for what kind of array I am going to need and how do I compare each inserted color in the array with last inserted colors. here is my code:

public Color GetUniqueRandomColor(int count){

for(int i = 0; i < count; i++)
{
Color.FromArgb(randomColor.Next(70, 200), randomColor.Next(100, 225), randomColor.Next(100, 230));
}

return Color.Red;}

this is how an element will look in the array:

Color [A=255, R=132, G=148, B=181]

As you can see my method still lacks the needed array and the algorithm to compare new inserted colors to it. Some help and tips will be appriciated!


With C# 3.5

public static Color[] GetUniqueRandomColor(int count)
{
    Color[] colors = new Color[count];
    HashSet<Color> hs = new HashSet<Color>();

    Random randomColor = new Random();

    for(int i = 0; i < count; i++)
    {
        Color color;
        while (!hs.Add(color = Color.FromArgb(randomColor.Next(70, 200), randomColor.Next(100, 225), randomColor.Next(100, 230))));
        colors[i] = color;
    }    

    return colors;
}

If you only have C# 2.0, you can substitute HashSet with a Dictionary, where the bool is only a placeholder that you won't use, but the while expression will get a little more complex

public static Color[] GetUniqueRandomColor(int count)
{
    Color[] colors = new Color[count];
    Dictionary<Color, bool> hs = new Dictionary<Color, bool>();

    Random randomColor = new Random();

    for (int i = 0; i < count; i++)
    {
        Color color;
        while (hs.ContainsKey(color = Color.FromArgb(randomColor.Next(70, 200), randomColor.Next(100, 225), randomColor.Next(100, 230)))) ;
        hs.Add(color, true);
        colors[i] = color;
    }

    return colors;
}


I will populate a list of "used color", so everytime you generate a new color before calling Color.FromArgb you can check it in your list. If the color exists you will call again the random function else you generate the color and add the value to the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜