Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: smooth collapse/expand form

Need your help (I'm stuck on searching for). I'm on Delphi Seattle, trying to make smooth resizing bottom of my form. In my case "resizing" is just a little collapse/expand like this:

enter image description here

How can I realize that?

I've tried use a TTimer:

procedure TForm1.Timer1Timer(Sender: TObject);
var
h, t: integer;
begin
t := Button10.Top + Button10.Height + 10; //slide TForm from/to this point
if t > h then
begin
h := h + 1;
Form1.Height := h;
end
else
begin
Timer1.Enabled := false;
end;
end;

... but it's looks very simple (no acceleration/deceleration) and works slow even with small interval.

like image 863
kazuser Avatar asked Apr 30 '16 10:04

kazuser


1 Answers

There's no need to get complicated with TTimers. This will take care of both collapsing and expanding forms including the smoothness that you require.

The trick is to calculate each step by taking the Target Size - Current Height and div 3 at each iteration, which will both accelerate the initial collapse or expand, then decelerate as the form gets closer to its target size.

procedure TForm1.SmoothResizeFormTo(const ToSize: integer);
var
  CurrentHeight: integer;
  Step: integer;
begin
  while Height <> ToSize do
  begin
    CurrentHeight := Form1.Height;

    // this is the trick which both accelerates initially then 
    // decelerates as the form reaches its target size
    Step := (ToSize - CurrentHeight) div 3; 

    // this allows for both collapse and expand by using Absolute
    // calculated value
    if (Step = 0) and (Abs(ToSize - CurrentHeight) > 0) then
    begin
      Step := ToSize - CurrentHeight;
      Sleep(50); // adjust for smoothness
    end;

    if Step <> 0 then
    begin
      Height := Height + Step;
      sleep(50); // adjust for smoothness
    end;
  end;
end;

procedure TForm1.btnCollapseClick(Sender: TObject);
begin
  SmoothResizeFormTo(100);
end;

procedure TForm1.btnExpandClick(Sender: TObject);
begin
  SmoothResizeFormTo(800);   
end;
like image 168
John Easley Avatar answered Oct 13 '22 17:10

John Easley