c# - 得到两个椭圆而不是一个
问题描述
所以我有一个代码需要在随机位置上绘制一个圆圈,并且它还需要保持在预定义的边界内。在我的代码中,我应该只画一个圆圈。在某些情况下,它只画了一个,但在其他情况下,它画了两个,我不知道为什么。
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);
}
解决方案
每当重新绘制表单时都会调用绘制事件,因此从您的角度来看,这是不可预测的。您最好将代码移动到加载事件中以生成位置:
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);
}
推荐阅读
- google-maps - 由于 PLACES_API_ACCESS_NOT_CONFIGURED 而自动完成小部件关闭
- javascript - 如何将图像添加到表格单元格
- xml - 如何将xml节点的值提取到powershell中的变量中?
- css - 仅在需要时加载 React 块 CSS
- python-3.x - TypeError:__init__() 为参数“实例”获取了多个值
- powershell - 函数 Get-IniContent 无法识别 - PowerShell 中的 INI 文件支持
- model - 为什么 model.forward(input) 和 model(input) 之间有不同的输出
- oracle - 创建用户时是否创建了任何默认的临时表空间?
- python - 包括 matplotlib figure() 搞砸了 Tkinter Checkbuttons()
- uima - 如果句子在模式之后有任何内容,则注释不匹配