c# - 得到两个椭圆而不是一个

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

最佳答案

每当 form is re-drawn 时,绘制事件就会被调用,所以从你的角度来看,这是不可预测的。您最好将代码移动到加载事件中以生成位置:

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

关于c# - 得到两个椭圆而不是一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255459/

相关文章:

.net - 包含更多信息的 TreeView 节点

C# JsonArray 到字符串(不是字符串数组。仅限字符串)

c# - 如何用 Dictionary<string, Func<>> 替换这个 switch-case ?

c# - 使用 IQueryable<T> 和自定义函数时优化对数据库的访问次数

c# - WinForm 中的 OpenID?

c# - 是否可以查询 ErrorProvider 是否设置了错误?

c# - 显示 View 时出错

c# - EXCEL XML 格式不是真的标准吗?

c# - MSDN 图表实时更改点值?

c# - 重新启动 Windows 操作系统后如何重置应用程序设置?