首页 > 解决方案 > 得到两个椭圆而不是一个

问题描述

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

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

标签: c#winforms

解决方案


每当重新绘制表单时都会调用绘制事件,因此从您的角度来看,这是不可预测的。您最好将代码移动到加载事件中以生成位置:

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

推荐阅读