我希望创建一个动态的图片框网格,一旦用户输入所需的行数和列数,就会生成该框。
例如如果用户输入3x3,则将在表格之类的网格中创建9个图片框。
当前,我的代码将创建所有所需的图片框,但将缩进每个新列中的第一个,从而创建一个尴尬的网格。
int rows = Convert.ToInt32(txtRow.Text);
int columns = Convert.ToInt32(txtColumn.Text);
// coordinates to place first box in the grid
int x = 211;
int y = 136;
int totalBoxes = rows * columns;
List<PictureBox> pictureBoxList = new List<PictureBox>();
for (int i = 0; i < totalBoxes; i++)
{
while (i < rows)
{
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(70, 60),
Location = new Point(x, y),
BorderStyle = BorderStyle.Fixed3D,
SizeMode = PictureBoxSizeMode.Zoom,
Visible = true
};
this.Controls.Add(picture);
pictureBoxList.Add(picture);
y = y + 59;
break;
}
while (i < columns)
{
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(70, 60),
Location = new Point(x, y),
BorderStyle = BorderStyle.Fixed3D,
SizeMode = PictureBoxSizeMode.Zoom,
Visible = true
};
this.Controls.Add(picture);
pictureBoxList.Add(picture);
x = x + 67;
break;
}
}
答案 0 :(得分:0)
您可以这样设置图片框位置:
PictureBox picture = new PictureBox
{
Location = new Point(i%columns * desiredWidth, i/columns * desiredHeight),
....
};
例如,图片框的大小为(70,60),您之间的间距可能会增加5像素,例如new Point(i%columns * 75, i/columns * 65) //desiredWidth=75, desiredHeight=65
您也可以给它一个开始缩进:
Location = new Point(x+ i%columns * desiredWidth,y+ i/columns * desiredHeight);
我会这样做:
int w=75, h = 65;
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(70, 60),
Location = new Point(x + i%columns * w, y + i/columns * h),
BorderStyle = BorderStyle.Fixed3D,
SizeMode = PictureBoxSizeMode.Zoom,
Visible = true
};
答案 1 :(得分:0)
您可以在代码中开始使用,从0到图片框总数循环使用。在这种情况下,您应该像Ashkan Mobayen Khiabani所示计算每个框的位置,如下所示:
// size of the boxes
Size size = new Size(70, 60);
int totalBoxes = rows * columns;
List<PictureBox> pictureBoxList = new List<PictureBox>();
for (int i = 0; i < totalBoxes; i++)
{
int curentColumn = i % columns;
int currentRow = i / columns;
int curentX = x + curentColumn * size.Width;
int curentY = y + currentRow * size.Height;
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = size,
Location = new Point(curentX, curentY),
BorderStyle = BorderStyle.Fixed3D,
SizeMode = PictureBoxSizeMode.Zoom,
Visible = true
};
this.Controls.Add(picture);
pictureBoxList.Add(picture);
}
但是,您也可以使用两个嵌套循环。首先穿过所有行,然后穿过所有列,像这样:
// size of the boxes
Size size = new Size(70, 60);
int totalBoxes = rows * columns;
List<PictureBox> pictureBoxList = new List<PictureBox>();
for (int row = 0; row < rows; row++)
{
int curentY = y + row * size.Height;
for (int col = 0; col < columns; col++)
{
int curentX = x + col * size.Width;
PictureBox picture = new PictureBox
{
Name = "pictureBox" + (row + col),
Size = size,
Location = new Point(curentX, curentY),
BorderStyle = BorderStyle.Fixed3D,
SizeMode = PictureBoxSizeMode.Zoom,
Visible = true
};
this.Controls.Add(picture);
pictureBoxList.Add(picture);
}
}
我个人更喜欢嵌套循环,因为它更易于阅读:)
从性能的角度来看,两种方法应该相同。