Problem in generating random colors - asp.net and C #

I need to generate generate random colors in Hex values โ€‹โ€‹in my asp.net application to draw a graph.

 Random random = new Random();
 color = String.Format("#{0:X6}", random.Next(0x1000000)); 

The code above generates random color codes. But my problem is some time when it generates almost similar colors for its previous colors. Due to the fact that I use it for graphics purposes, I need to generate completely different colors. Any ideas ....

+5
source share
5 answers

, ... , , . KMan, , , , , ( , ), , .

, "" , .

  • ( , , )
  • , ( ), .

- , .
, , .
, (RNG), , - RNG, ...

  const int minTotalDiff = 200;    // parameter used in new color acceptance criteria
  const int okSingleDiff = 100;    // id.

  int prevR, prevG, prevB;  // R, G and B components of the previously issued color.
  Random RandGen = null;

  public string GetNewColor()
  {
      int newR, newG, newB;

      if (RandGen == null)
      {
          RandGen = new Random();
          prevR = prevG = prevB = 0;
      }

      bool found = false;
      while (!found)
      {
          newR = RandGen.Next(255);
          newG = RandGen.Next(255);
          newB = RandGen.Next(255);

          int diffR = Math.Abs(prevR - newR);
          int diffG = Math.Abs(prevG - newG);
          int diffB = Math.Abs(prevB - newB);

          // we only take the new color if...
          //   Collectively the color components are changed by a certain
          //   minimum
          //   or if at least one individual colors is changed by "a lot".
          if (diffR + diffG + diffB >= minTotalDiff
              || diffR >= okSingleDiff
              || diffR >= okSingleDiff
              || diffR >= okSingleDiff
          )
            found = true;
        }

       prevR = newR;
       prevG = newG;
       prevB = newB;

      return String.Format("#{0:X2}{0:X2}{0:X2}", prevR, prevG, prevB);
  }
+4

Try

Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));

- EDIT -

mjv:

public class RandomColor
{
    Random _random;
    public RandomColor()
    {
        _random = new Random();
    }

    public Color GetNext()
    {
        return Color.FromArgb(_random.Next(0, 255), _random.Next(0, 255), _random.Next(0, 255));
    }
}

:

colorRandom.GetNext();
+5

, , , ... , , , , .

, , ( )

for (some loop logic)
{
  Random r = new Random();
  int myRandomNumber = Random.Next()
}

, (, 8 ), , 9 .. , :

Random r = new Random();
for (some loop logic)
{
  int myRandomNumber = Random.Next()
}

, , , Random , Random , , , . ( ), , ( ) , , .

, , ... , , , , , .

-

, :

http://geekswithblogs.net/kakaiya/archive/2005/11/27/61273.aspx

+3
Random r=new Random();
var newCol=(r.Next(0,256)<<16)+(r.Next(0,256)<<8)+(r.Next(0,256));

, Next

+1
+1

All Articles