面板上图片框的随机位置

时间:2017-05-04 21:25:54

标签: c# picturebox

我想为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 个答案:

答案 0 :(得分:1)

您可以通过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)

如果你想移动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));

如果您希望在首次加载Form1对象时执行该操作,则需要将该小代码段放在Form_Load事件中