Random colors not so random

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello all, I'm trying to program a random color generator as follows:

Color = Color.FromArgb( (rnd.Next(0,255)), (rnd.Next(0,255)),
(rnd.Next(0,255)) );

When executing, the colors generated from the above line always appear the
same, certainly not random. What is the correct way to generate random
colors?
 
Lionel,

From the help...
Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.

HTH,
Brian
 
Brian P. Hammer said:
Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.

Mhm... The OP doesn't seem to use VB.NET's 'Rnd' function, thus no call to
'Randomize' is required.
 
Leave it to a newbie to through something out. ;-)

That's why I generally ask more then I contribute.

Brian
 
Random rnd=new Random((int)DateTime.Now.Millisecond);

SolidBrush sb=new
SolidBrush(Color.FromArgb(rnd.Next(0,255),rnd.Next(0,255),rnd.Next(0,255)));


--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Bob Powell said:
Random rnd=new Random((int)DateTime.Now.Millisecond);

Why do that? Just use:

Random rnd = new Random();

and it'll be time-based already.

However, the important thing is to reuse that Random object, rather
than creating a new one for each use - otherwise if several uses are
within a very short space of time, you'll create several Random objects
with the same seed, and they'll all give the same results.
 
Back
Top