画矩形只画1点

时间:2018-12-19 19:53:34

标签: c# .net draw system.drawing

我写了一些代码,这些代码生成一个随机点,并且还制作了随机矩形。 所有调试似乎都可以,但是代码只绘制了一个矩形。

查看我的代码,并告诉我什么地方不对。

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

1 个答案:

答案 0 :(得分:0)

您的代码很可能看起来像这样:

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);
}
相关问题