得到两个椭圆而不是一个

时间:2018-05-09 14:06:30

标签: c# winforms

所以我有一个代码需要在随机位置绘制一个圆,并且它还需要保留在预定义的边框中。在我的代码中,我应该只画一个圆圈。在某些情况下,它只绘制一个,但在其他情况下,它绘制了两个,我不知道为什么。 Click for photo

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Random r = new Random();

    int leftX = 20;
    int topY = 60;
    int width = this.Width - (3 * leftX);
    int height = this.Height - (int)(2.5 * topY);

    float x = r.Next(20, width - 100);
    float y = r.Next(60, height - 100);

    Rectangle rect = new Rectangle((int)x, (int)y, 100, 100);
    g.DrawRectangle(new Pen(Color.Black), rect); //rectangle around ellipse
    g.DrawRectangle(new Pen(Color.Black, 3), leftX, topY, width, height); //border rectangle

    g.FillEllipse(new SolidBrush(Color.Black), rect);
}

1 个答案:

答案 0 :(得分:2)

每当form is re-drawn时都会调用paint事件,因此从您的角度来看,这是不可预测的。您最好移动代码以生成加载事件中的位置:

float x;
float y;
private void Form1_Load(object sender, System.EventArgs e)
{
    Random r = new Random();
    x = r.Next(20, width - 100);
    y = r.Next(60, height - 100);

}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;

    int leftX = 20;
    int topY = 60;
    int width = this.Width - (3 * leftX);
    int height = this.Height - (int)(2.5 * topY);

    Rectangle rect = new Rectangle((int)x, (int)y, 100, 100);
    g.DrawRectangle(new Pen(Color.Black), rect); //rectangle around ellipse
    g.DrawRectangle(new Pen(Color.Black, 3), leftX, topY, width, height); //border rectangle

    g.FillEllipse(new SolidBrush(Color.Black), rect);
}