Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this simple C# tryout work [duplicate]

this creates streaks instead of dots. why ? I am trying to paint individual pixels. another method was also tried (using fillrectangle) , which also didn't give the desired result, got bars instead of dots.

protected override void OnPaint(PaintEventArgs pea )
    {

         Graphics g = pea.Graphics ;

         for ( int y = 1 ; y <= Width ; y++ )
         {
            for (  int x  =  1  ; x <=  Height    ; x++ )
            {
                System.Random rand = new  System.Random() ;
                Color c =   (Color.FromArgb(rand.Next(256),
                                    rand.Next(256),
                                    rand.Next(256)));
            // SolidBrush myBrush = new SolidBrush(c);
            // g.FillRectangle(myBrush, x, y, 1, 1);


                 Bitmap pt = new Bitmap(1, 1);
                 pt.SetPixel(0, 0, c);
                 g.DrawImageUnscaled(pt, x, y);

            }
        }

}

what is happening here ?

like image 567
user257412 Avatar asked Jul 03 '26 11:07

user257412


2 Answers

You should not create a new Random object each time. Since that will give you the exact same "random" numbers repeated over and over.

Instead use the same Random object and just call Next on in.

like image 56
Martin Wickman Avatar answered Jul 05 '26 00:07

Martin Wickman


You need to create the System.Random object outside the loops. When initialized inside the loop it keep getting the same seed (since it's initialized according to the system clock, which would still have the same value) and therefore the same color.

like image 32
interjay Avatar answered Jul 04 '26 23:07

interjay