Wednesday, September 28, 2011

Dynamically Calculate Control Dimension at UI

Calculate the dimension of controls at UI in term of rows*columns. This accepts parent container width/height and number of controls to draw. You may also provide what ratio you need for controls.


/// Calculate control dimension as per parent size and required ratio
/// param name="ParentWidth">Parent control width
/// param name="ParentHeight">Parent control height
/// param name="TotalControls">Total control
/// param name="RatioX">X ratio of control to maintain
/// param name="RatioY">Y ratio of control to maintain
/// param name="TotalColumns">get columns
/// param name="TotalRows">get rows
public void CalculateDimensions(int ParentWidth, int ParentHeight, int TotalControls, int RatioX, int RatioY, out int TotalColumns, out int TotalRows)
{
TotalColumns = TotalRows = 1;

      double areaRatio = Math.Sqrt(((double)(ParentHeight * RatioX) / (double)(ParentWidth * RatioY)) / (double)TotalControls);
      double expectedWidth = areaRatio * ParentWidth;
      double expectedHeight = areaRatio * ParentHeight;

      if (ParentWidth > ParentHeight)
            TotalColumns = (int)Math.Ceiling((double)ParentWidth / (double)expectedWidth);
      else
            TotalRows = (int)Math.Ceiling((double)ParentHeight / (double)expectedHeight);

bool isOK = false;
      while (!isOK)
      {
            if (ParentWidth > ParentHeight)
            {
                  TotalRows = (int)(Math.Ceiling((double)TotalControls / (double)TotalColumns));
                  if (TotalColumns >= TotalRows) isOK = true; else TotalColumns++;
            }
            else
            {
                  TotalColumns = (int)(Math.Ceiling((double)TotalControls / (double)TotalRows));
                  if (TotalRows >= TotalColumns) isOK = true; else TotalRows++;
            }
       }
}