Wednesday, November 25, 2009

Dynamically Calculate Control Locations at UI

Calculate locations and size for UI controls in any container at run time. This helps when you want to draw UI controls at run time, so you will only required rows*columns dimension, the code below will automatically calculates the size and location your controls will have.

Size size;
List<Point> points;
GetControlLocations(this.panel1.Width, this.panel1.Height, 3, 3, 5, out size, out points);
Following is the piece of code that performs the calculation
///summary>
///Calculate location and size or controls in a specified container
////summary>
///name="ParentWidth">Parent container width/param
///name="ParentHeight">Parent container height/param
///name="TotalRows">Number of rows/param
///name="TotalColumns">Number of columns/param
///name="Gap">Gap between controls/param
///name="ControlSize">Size of a control/param
///name="ControlLocations">Locations of controls/param


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++;
}
}

No comments:

Post a Comment