所以我有一段代码需要在随机位置绘制一个圆,并且它还需要保持在预定义的边界内。在我的代码中,我应该只画一个圆圈。在某些情况下,它只绘制一个,但在其他情况下,它绘制两个,我不知道为什么。
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/