Introduction
This article discusses how to calculate locations and size for UI controls in any container.
Background
This helps when you want to draw UI controls at run time, without knowing the exact count of required controls.
Using the Code
Specify the Size and List<Point> variables to be set by out parameters and put the required controls count in requiredControlsCount.
this.Size.Width can be replaced with the container width on which you want to draw controls.
Modify the If statements as required. This will affect the number of rows and columns you want for a range.
For a count of 7 to 9 controls, the following code will generate 3 rows and 3 columns.
Size controlSize = new Size();
List<Point> controlLocations = new List<Point>();
int requiredControlsCount = 9;
if (requiredControlsCount == 1)
GetControlLocations(this.Size.Width, this.Size.Height, 1,
1, 5, out controlSize, out controlLocations);
else if (requiredControlsCount > 1 && requiredControlsCount <= 4)
GetControlLocations(this.Size.Width, this.Size.Height, 2,
2, 5, out controlSize, out controlLocations);
else if (requiredControlsCount > 4 && requiredControlsCount <= 6)
GetControlLocations(this.Size.Width, this.Size.Height, 3,
2, 5, out controlSize, out controlLocations);
else if (requiredControlsCount > 6 && requiredControlsCount <= 9)
GetControlLocations(this.Size.Width, this.Size.Height, 3,
3, 5, out controlSize, out controlLocations);
else if (requiredControlsCount > 9 && requiredControlsCount <= 12)
GetControlLocations(this.Size.Width, this.Size.Height, 4,
3, 5, out controlSize, out controlLocations);
else if (requiredControlsCount > 12 && requiredControlsCount <= 16)
GetControlLocations(this.Size.Width, this.Size.Height, 4,
4, 5, out controlSize, out controlLocations);
GetControlLocations will calculate the required size and array of locations of all controls, and will put them in out parameter.
public static void GetControlLocations(int ParentWidth,
int ParentHeight, int TotalRows, int TotalColumns,
int Gap, out Size ControlSize, out List<Point> ControlLocations)
{
int column = 1;
int row = 1;
int width = (int)((ParentWidth - (TotalRows + 1) * Gap) / TotalRows);
int height = (int)((ParentHeight - (TotalColumns + 1) * Gap) / TotalColumns);
int startX = Gap;
int startY = Gap;
ControlSize = new Size(width, height);
ControlLocations = new List<Point>();
for (int i = 0; i < TotalRows * TotalColumns; i++)
{
if (column > TotalRows)
{
column = 1;
row++;
}
ControlLocations.Add(new Point((width * (column - 1)) +
(Gap * column), (height * (row - 1)) + (Gap * row)));
column++;
}
}
History
- 13th March, 2009: Initial post