你不需要这样计算位置,我们应该使用一些布局控制来解决这个问题。只需添加 2 Panels
,第一个停靠在表单的左侧,第二个停靠在表单的右侧。
panel1.Dock = DockStyle.Left;
panel2.Dock = DockStyle.Right;
panel1.Width = panel2.Width = 100;
现在,您只需要添加 4 个图片框panel1
和 4 个图片框到panel2
,同样使用Dock
如下属性:
for (int i = 0; i < pbs.Length; i++) {
pbs[i].Size = new Size(100, 100);
pbs.Margin = new Padding(0, 0, 0, 60);
pbs.Dock = DockStyle.Top;
Panel p = i < 4 ? panel1 : panel2;
p.Controls.Add(pbs[i]);
pbs.BringToFront();
}
您也可以使用FlowLayoutPanel
代替Panel
,它会自动为您停靠控件。
flowLayoutPanel1.Dock = DockStyle.Left;
flowLayoutPanel2.Dock = DockStyle.Right;
flowLayoutPanel1.Width = flowLayoutPanel2.Width = 100;
flowLayoutPanel1.FlowDirection = flowLayoutPanel2.FlowDirection = FlowDirection.TopDown;
for (int i = 0; i < pbs.Length; i++) {
pbs[i].Size = new Size(100, 100);
pbs.Margin = new Padding(0, 0, 0, 60);
Control p = i < 4 ? flowLayoutPanel1 : flowLayoutPanel2;
p.Controls.Add(pbs[i]);
}