画矩形只画1点

Draw rectangles just draw 1 point

我写了一些生成随机点和随机矩形的代码。 所有调试似乎都正常,但代码只绘制了 1 个矩形。

查看我的代码并告诉我哪里出了问题。

private void btnRun_Click(object sender, EventArgs e)
{
    Graphics g = pnlWarZone.CreateGraphics();
    if (int.Parse(txtGenerationCount.Text) > 0)
    {
        RectangleF[] rects = new RectangleF[int.Parse(txtGenerationCount.Text)];

        for (int i = 0; i < int.Parse(txtGenerationCount.Text); i++)
        {
            rects[i] = new RectangleF(GeneratePoint(),new SizeF(4,4));
        }

        g.FillRectangles(new SolidBrush(Color.Blue), rects);
    }
}

更新:这是生成点的方法

private Point GeneratePoint()
{
    Random r = new Random();
    //return random.NextDouble() * (maxValue - minValue) + minValue;
    var x =r.Next(_rectangles[0].X, _rectangles[0].Width);
    var y =r.Next(_rectangles[0].Y, _rectangles[0].Height);
    return new Point(x,y);
}

您的代码很可能如下所示:

private Point GeneratePoint() {
  Random rnd = new Random();
  int x = rnd.Next(0, pnlWarZone.ClientSize.Width);
  int y = rnd.Next(0, pnlWarZone.ClientSize.Height);
  return new Point(x, y);
}

您要做的是只生成一个新的 Random 对象一次,并且以后总是重新使用该变量:

Random rnd = new Random();

private Point GeneratePoint() {      
  int x = rnd.Next(0, pnlWarZone.ClientSize.Width);
  int y = rnd.Next(0, pnlWarZone.ClientSize.Height);
  return new Point(x, y);
}