Delphi element alignment - center

Flash Thunder picture Flash Thunder · May 19, 2014 · Viewed 7.2k times · Source

There seems to be align property that works really well, but is is possible to align element so all elements on panel would be aligned to center all on bottom of each other if they all have less than size of container? Something like top-center-center.

Something like this:

Something like this

Or at least horizontally, and vertically they can have 100%.

Answer

Remy Lebeau picture Remy Lebeau · May 19, 2014

Put the elements into their own container, such as a TPanel or TFrame, that is a child of your main container. Set the child container's Align property to alCustom and use the parent container's OnAlignPosition event to keep the child container centered to itself:

// Panel1 is the Parent container for the child panel...
procedure TMyForm.Panel1AlignPosition(Sender: TWinControl; Control: TControl;
  var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect;
  AlignInfo: TAlignInfo);
begin
  if Control = ChildPanel then
  begin
    NewLeft := AlignRect.Left + ((AlignRect.Width - Control.Width) div 2);
    NewTop := AlignRect.Top + ((AlignRect.Height - Control.Height) div 2);
  end;
end;