首页 > 解决方案 > 如何通过c#中的for循环来扩大绘制矩形的大小?

问题描述

我无法通过 for 循环膨胀原始绘制的矩形。我想可能将原始绘制的矩形存储到一个数组中并从他们的循环中存储它,但它不能正常工作。

 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);
      }

只显示了 2 个绘制的矩形,而它应该是 5 个。我无法修改 rec2

标签: c#arrayswinformsfor-loopdrawrectangle

解决方案


您正在使用相同的 rec1 作为基础进行膨胀。所以在第一个循环之后,新矩形的大小总是相同的。

你需要使用rec2

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

但是使用这种方法,您应该颠倒调用的顺序来绘制初始矩形

  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);
  }

推荐阅读