Search code examples
c#arrayswinformsfor-loopdrawrectangle

How to inflate the size of drawn rectangle throught a for-loop in c#?


I cannot inflate the original drawn rectangle through for-loop. I wanted to maybe store the original drawn rectangle into an array and from their loop it, but it did not work properly.

 loop_txtbx.Text = 5
 parameter_txtbx.Text = 20

 int[] rec = new int[loops];

 int xCenter = Convert.ToInt32(startX_coord_txtbx.Text);
 int yCenter = Convert.ToInt32(startY_coord_txtbx.Text); 

 int width = Convert.ToInt32(width_txtbx.Text);
 int height = Convert.ToInt32(height_txtbx.Text);

 //Find the x-coordinate of the upper-left corner of the rectangle to draw.
  int x = xCenter - width / 2;

 //Find y-coordinate of the upper-left corner of the rectangle to draw. 
  int y = yCenter - height / 2;

  int loops = Convert.ToInt32(loop_txtbx.Text);
  int param = Convert.ToInt32(parameter_txtbx.Text);

   // Create a rectangle.
  Rectangle rec1 = new Rectangle(x, y, width, height);

   // Draw the uninflated rectangle to screen.
  gdrawArea.DrawRectangle(color_pen, rec1);   

  for (int i = 0; i < loops; i++)
      {

      // Call Inflate.
      Rectangle rec2 = Rectangle.Inflate(rec1, param, param);

      // Draw the inflated rectangle to screen.
      gdrawArea.DrawRectangle(color_pen, rec2);
      }

Only 2 drawn rectangles are shown, while it was supposed to be 5. I cannot manage to modify rec2


Solution

  • You are using the same rec1 as a base to inflate. So after the first loop you get always the same size for the new rectangle.

    You need to use rec2

    Rectangle rec2 = rec1;
    for (int i = 0; i < loops; i++)
    {
        rec2 = Rectangle.Inflate(rec2, param, param);
        ....
    }
    

    But with this approach you should invert the order of the calls to draw the initial rectangle

      Rectangle rec2 = rec1;
      for (int i = 0; i < loops; i++)
      {
           // Draw the current rectangle to screen.
           gdrawArea.DrawRectangle(color_pen, rec2);
    
           // Call Inflate.
           rec2 = Rectangle.Inflate(rec2, param, param);
      }