在C#中对齐数组中的标签以形成网格

时间:2015-11-11 05:15:00

标签: c# label picturebox

我创建了一系列黑色标签,并将它们显示在图片框上。不幸的是,我无法在黑线的每个交叉点直接排列它们。我怎么能这样做?

InitializeComponent();

        int x = pictureBox1.Location.X;

        int y = pictureBox1.Location.Y;

        // create 361 labels, set their properties
        for (int i = 0; i < 361; i++)
        {
            board[i] = new Label();
            board[i].Parent = pictureBox1;
            board[i].Location = new Point(x, y);
            board[i].Name = "label" + i;
            board[i].Text = "0";
            board[i].BackColor = Color.Black;
            //set size of labels
            board[i].Size = new Size(31,31);

        }


        // set the position of the label
        foreach (Label i in board)
        {
            //set distance between labels
            if (x >= 1024)
            {
                x = pictureBox1.Location.X;
                y += 52;
            }

            else
            {
                x += 52;
            }


            this.Controls.Add(i);
            i.BringToFront();
            i.Location = new Point(x, y);
        }

enter image description here

1 个答案:

答案 0 :(得分:1)

据我了解你的问题,看到了你的代码。

您正在创建标签 Location(x,y) x = 100y = 0

在下一个循环中

    foreach (Label i in board)
    {
        if (x >= 1024)
        {
            x = 0;
            y += i.Height + 55;
        }

        else if (y >= 1024)
        {
            y = 0;
            x += i.Width + 55;
        }
    }

你的条件都不会成真,因为你的x = 100且y = 0 所以位置将保持不变,所有标签将位于同一位置

如果要显示国际象棋网格,请参阅此方法 Chess Grid in Winforms

如果要在行的交叉点上显示标签,请修改代码

        x = PictureBox1.Location.X + 55;
        y = pictureBox1.Location.Y + 55;
        for (int i = 0; i < 361; i++)
            {
                board[i] = new Label();
                board[i].Parent = pictureBox1;
                board[i].Location = new Point(x,y); 
                board[i].Name = "label" + i;    
                board[i].Text = "0";
                board[i].BackColor = Color.Black;
                board[i].Size = new Size(55,55); //Define size of label according to your choice 
                if(x >= 1024)
                {
                  x = PictureBox1.Location.X + 55; //Start position
                  y += 55;                    // Step to next line
                }
                else
                  x += 55;                   //jump to next horizontal box
            }

我希望这会有所帮助