The following code snippet only returns in grayscale. I have been troubled by this for the majority of the day. Any thoughts on the reason why?
using System.Drawing;
private Graphics _g;
public Form1()
{
InitializeComponent();
_g = pictureBox1.CreateGraphics();
}
private void x()
{
System.Drawing.Rectangle r = CreateCircle(e);
SolidBrush brsh = ChooseFillColor();
_g.FillEllipse(brsh, r);
}
private SolidBrush ChooseFillColor()
{
return new SolidBrush(Color.FromArgb(RandomNumber(255), RandomNumber(255), RandomNumber(255)));
}
private int RandomNumber(int max)
{
Random random = new Random();
return random.Next(max);
}
You initialize a new Random object every time. Since it uses the current time by default as its seed, and you call it so quickly that the time doesn’t change (on Windows, the timer’s accuracy is about 15 milliseconds), you always get the same random number. Create a static Random object in your class instead.
EDIT: Also, consider making your RandomNumber method static as well, or put it (along with the static Random object) in a static class.