面板上图片框的随机位置

时间:2022-05-06 00:24:41

I want to generate a random position for my PictureBox which is in a Panel. I load my page with C#. This is my code for the PictureBox. How can I have a random position for it?

我想为Panel中的PictureBox生成一个随机位置。我用C#加载我的页面。这是我的PictureBox代码。我怎么能有一个随机的位置呢?

private void Form1_Load(object sender, EventArgs e)
{            
    PictureBox pictureboxtroll = new PictureBox();
    pictureboxtroll.Size = new System.Drawing.Size(70, 70);
    pictureboxtroll.BackColor = Color.Green;
    this.Controls.Add(pictureboxtroll);
}

2 个解决方案

#1


1  

If you want to move the position of the pictureBox (X and Y coordinates) you have to acces it through the Location property like this:

如果要移动pictureBox(X和Y坐标)的位置,则必须通过Location属性访问它,如下所示:

Random rand = new Random();
picturebox.Location.X = new Point(rand.Next(0,this.Widht));
pictureBox.Location.Y = new Point(rand.Next(0,this.Height));

And if you want that to execute when the Form1 object first loads then you need to place that little code snippet in the Form_Load event

如果你想在Form1对象首次加载时执行,那么你需要将那个小代码片段放在Form_Load事件中

#2


1  

You can set the position of an element through its Location property:

您可以通过其Location属性设置元素的位置:

// generate random position
Random random = new Random();
var viewRange = this.Size - pictureboxtroll.Size;
var left = random.Next(0, viewRange.Width);
var top = random.Next(0, viewRange.Height);

// set the random position
pictureboxtroll.Location = new Point(left, top);

#1


1  

If you want to move the position of the pictureBox (X and Y coordinates) you have to acces it through the Location property like this:

如果要移动pictureBox(X和Y坐标)的位置,则必须通过Location属性访问它,如下所示:

Random rand = new Random();
picturebox.Location.X = new Point(rand.Next(0,this.Widht));
pictureBox.Location.Y = new Point(rand.Next(0,this.Height));

And if you want that to execute when the Form1 object first loads then you need to place that little code snippet in the Form_Load event

如果你想在Form1对象首次加载时执行,那么你需要将那个小代码片段放在Form_Load事件中

#2


1  

You can set the position of an element through its Location property:

您可以通过其Location属性设置元素的位置:

// generate random position
Random random = new Random();
var viewRange = this.Size - pictureboxtroll.Size;
var left = random.Next(0, viewRange.Width);
var top = random.Next(0, viewRange.Height);

// set the random position
pictureboxtroll.Location = new Point(left, top);