使用C#将图像随机放置在特定位置

Randomly put an image in specific places using C#

我对 C# 完全陌生,所以我希望我的问题没有完全偏离。

如上图所示,我有一个表格,其中有一个table(image)和一个button。在项目的资源中,我有另一个图像 (black_rectangle.png),它是一个黑色矩形,与每个 table 的单元格大小完全相同。这就是我想要实现的目标: 每次单击 'Again' 按钮时,我希望六个黑色矩形以随机方式覆盖每列中的两个树单元格。例如,在第一次尝试后,table 可能如下所示:

我基本上卡在了开头:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
        List<PictureBox> items = new List<PictureBox>();
        PictureBox newPic= new PictureBox();
        newPic.Height = 50;
        newPic.Width = 50;
        newPic.BackColor = Color.Maroon;

        int x = rand.Next(10, this.ClientSize.Width - newPic.Width);
        int y = rand.Next(10, this.ClientSize.Height - newPic.Height);
        newPic.Location = new Point(x, y);
    }
}

假设 table(图像)在“pictureBox1”中,您可以尝试类似的操作:

private Random rnd = new Random();
private List<int> positions = new List<int> { 0, 1, 2 };
private List<PictureBox> prevBoxes = new List<PictureBox>();

private void button1_Click(object sender, EventArgs e)
{
    prevBoxes.ForEach(pb => pb.Dispose()); // remove previous boxes
    for(int col=0; col<3; col++)
    {
        positions = positions.OrderBy(i => rnd.Next()).ToList(); // shuffle positions
        for(int i=0; i<2; i++)
        {
            PictureBox newPic = new PictureBox();
            newPic.Height = 50;
            newPic.Width = 50;
            newPic.BackColor = Color.Maroon;
            newPic.Location = new Point(pictureBox1.Left + (col * 50), pictureBox1.Top + (positions[i] * 50));
            this.Controls.Add(newPic);
            newPic.BringToFront();
            prevBoxes.Add(newPic);
        }               
    }            
}

输出: