Calc Object Widths

TECH TIP: Calculating the Widths of Components at Run-Time

The example below shows how to calculate the widths of report components and position them horizontally.

This example procedure accepts a list of CustomText descendents and positions them flush left, one after
the other.  The Left position of the first component is used as the starting point.

procedure ppAlignHorizontal(aComponentList: TList);
var
  lCustomText: TppCustomText;
  lBitmap: TBitmap;
  liPosition := 0;

begin
  
  if (aComponentList = nil) then Exit;

  if (aComponentList.Count = 0) then Exit;

  lBitmap := TBitmap.Create;
  liPosition := TppCustomText(aComponentList[0]).spLeft;

  for liIndex := 0 to aComponentList.Count - 1 do
    begin
      lCustomText := TppCustomText(aComponentList[liIndex]);

      {set components screen pixel left}
      lCustomText.spLeft := liPosition;

      {calc next position}
      lBitmap.Canvas.Font := lCustomText.Font;

      liTextWidth := lBitmap.Canvas.TextWidth(lComponent.Caption);

      liPosition := liPosition + liTextWidth;          
    end;

  lBitmap.Free;

end;