​ 关于动画移动矩形的例子 - 回复 "ps8.0" 同学 ​


问题来源:​​https://blog.51cto.com/u_14617575/2835198​



首先, 实现这个问题有两种方法:


1、边擦边画; 2、先在内存绘图然后再复制到前台, 就是所谓的双倍缓存.


本例使用的是比较传统的 "边擦边画" 法, 但现在更提倡使用 "双倍缓存" 法.



本例效果图(实际的动画效果比这个 gif 要好一些):


关于动画移动矩形的例子 - 回复_linux



代码文件:


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

var
pt1,pt2: TPoint; {两个点}
n: Integer = 20; {用于正方形大小}
cvs: TCanvas; {画布}
a,b,ai,bi: Single;

procedure TForm1.FormCreate(Sender: TObject);
begin
Timer1.Enabled := False;
Timer1.Interval := 25;

Button1.Caption := '画正方形';
Button2.Caption := '移动';
Button3.Caption := '暂停';

cvs := TCanvas.Create;
cvs.Handle := GetDC(Handle);

Self.Color := clWhite;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
{给两个点赋值}
pt1.X := 30;
pt1.Y := 30;
pt2.X := ClientWidth - 30;
pt2.Y := ClientHeight - 30;

{记下起始点的位置}
a := pt1.X;
b := pt1.Y;

{算出每次的偏移量}
ai := (pt2.X-pt1.X)/100; {假如用 100 次移动完毕}
bi := (pt2.Y-pt1.Y)/100;

{在第一点位置画出矩形, 使用随机颜色}
Randomize;
cvs.Pen.Color := Random($FFFFFF);
cvs.Pen.Width := 4;
cvs.Rectangle(Round(a-n), Round(b-n), Round(a+n), Round(b+n));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
Timer1.Enabled := True;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
Timer1.Enabled := False;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
if a >= pt2.X then
begin
Timer1.Enabled := False;
Exit;
end;

{擦除上一个}
cvs.Pen.Mode := pmNotXor;
cvs.Rectangle(Round(a-n), Round(b-n), Round(a+n), Round(b+n));

{再画}
cvs.Pen.Mode := pmCopy;
a := a+ai;
b := b+bi;
cvs.Rectangle(Round(a-n), Round(b-n), Round(a+n), Round(b+n));
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
cvs.Free;
end;

end.

窗体文件:


object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 214
ClientWidth = 335
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poDesktopCenter
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 252
Top = 8
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object Button2: TButton
Left = 252
Top = 39
Width = 75
Height = 25
Caption = 'Button2'
TabOrder = 1
OnClick = Button2Click
end
object Button3: TButton
Left = 252
Top = 70
Width = 75
Height = 25
Caption = 'Button3'
TabOrder = 2
OnClick = Button3Click
end
object Timer1: TTimer
OnTimer = Timer1Timer
Left = 168
Top = 80
end
end