0

I am using c# to and a while loop to draw a series of rectangles inside of each other and want the color to be different for each rectangle but for some reason the loop's color stays the same everytime it goes through the loop. If I re-execute the loop it will change colors but I need it to change color when it iterates my controlling variable.

This is what i have:

private Color GetRandomColor()
    {
        Random rnd = new Random();
        return Color.FromArgb(rnd.Next(0,255), rnd.Next(0,255), rnd.Next(0,255));
    }



        x1 = 400;
        y1 = 50;
        x2 = 100;
        y2 = 100;

        while (y2 >= 2)
        {

            myPen.Color = GetRandomColor();


            graphicObj.DrawRectangle(myPen, x1, y1, x2, y2);

            x1 = x1 + 2;
            y1 = y1 + 2;
            x2 = x2 - 4;
            y2 = y2 - 4;
        }
Alecks
  • 129
  • 1
  • 7
  • You use the same `myPen` for all the objects, therefore each object that you draw with `myPen` will have the same colour. It's a basic **reference-type** issue. – Der Kommissar Jun 03 '15 at 14:16
  • 1
    http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number – JohnLBevan Jun 03 '15 at 14:16
  • @GrantWinney All the `Rectangle` objects have the same reference to `myPen`, as far as the current code stands. Therefore, when you change the `Colour` on the `myPen` object, all the rectangles see the *same* update. However, all that said, your issue is likely the use of the `Random` class. – Der Kommissar Jun 03 '15 at 14:21

0 Answers0