Delphi:平滑折叠/展开表单

7
需要您的帮助(我在寻找中卡住了)。我正在使用Delphi Seattle,尝试使我的窗体底部平滑调整大小。在我的情况下,“调整大小”只是像这样的小折叠/展开:

enter image description here

我该如何实现这一点?

我尝试使用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;

...但它看起来非常简单(没有加速/减速),即使使用小间隔也运行缓慢。


2
本地变量(如ht)在调用之间不是持久的(这里是计时器事件)。它们分配在堆栈上,并在过程退出时停止存在。在重复调用中,您可能会很幸运地重用相同的内存,但依赖于此是错误的。TTimer 分辨率为 10ms - 15ms,尽管您可以将其设置为 1ms。它也是基于消息的,计时器消息是低优先级的。对于更准确和更高性能的计时器,请使用 winapi 多媒体计时器。最后,简单的代码可能看起来简单,为什么您希望它显示加速/减速呢? - Tom Brunberg
1个回答

8

不必使用复杂的TTimers。这段代码可以同时解决展开和折叠表单,包括你需要的流畅效果。

关键在于通过每次迭代计算每个步骤,即目标大小-当前高度并将其除以3,这样既可以加速初始折叠或展开,又可以随着表单接近目标大小而减速。

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;

1
非常感谢John!这正是我想要看到的! - kazuser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接