Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating random colors (System.Drawing.Color)

Tags:

c#

asp.net

I am tring to create random drawing colors. There is an error. Could you help me about this code.

        private Random random;

        private void MainForm_Load(object sender, EventArgs e)
        {
            random = new Random();
        }

        private Color GetRandomColor()
        {
            return Color.FromArgb(random.Next(0, 255), random.Next(0,255),random.Next(0,255));
        // The error is here
        }  

        public SolidBrush brushGet()
        {
            SolidBrush oBrush = new SolidBrush(GetRandomColor());
            return oBrush;
        }
like image 451
Hzyf Avatar asked Dec 11 '11 16:12

Hzyf


4 Answers

I don't see any problems with the above code, other than the Random object not being initialized before it is called to. There is also absolutely no need to initialize it in the Load event of the form; it can be done right when it's declared:

private static readonly Random Random = new Random();

Personally I'd not declare it on local scope, as far as I know you end up with the same value every time if you go about it that way. I also personally don't see the need of overcomplicating things; generating random numbers everytime and using the Color.FromAgb() method you should be fine.

like image 180
aevitas Avatar answered Sep 30 '22 07:09

aevitas


This Worked for me (at the GetRandomColor):

Random random = new Random();
return Color.FromArgb((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
like image 27
GabrielTK Avatar answered Sep 30 '22 05:09

GabrielTK


    private Color color;
    private int b;
    public Color Random()
    {
        Random r = new Random();
        b = r.Next(1, 5);
        switch (b)
        {
            case 1:
                {
                    color = Color.Red;
                }
                break;
            case 2:
                {
                    color = Color.Blue;
                }
                break;
            case 3:
                {
                    color = Color.Green;
                }
                break;
            case 4:
                {
                    color = Color.Yellow;
                }
                break;
        }

        return color;
    }
like image 23
Dell Studio Avatar answered Sep 30 '22 06:09

Dell Studio


I guess brushGet gets called before MainForm_Load could have created random.

like image 35
kol Avatar answered Sep 30 '22 07:09

kol