Mega Code Archive

 
Categories / Delphi / Examples
 

An easy pulsing effect

Title: An easy pulsing effect Question: How can I create a pulsing effect on a color in my program easily? Answer: -First sorry for my English. It is easy because you only have to set a TDateTime variable at the beginning of your program, and then you are able to use pulsing colors like in QBASIC the color codes after 16. But it's finer. So I show a program code. On Form1 there is a Timer1. Its interval is 50. Then the code should look like: {___________Creating pulsing colors - the easiest way ____________by Attila Tanyi (tatil@freemail.hu) } unit uPulse; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TForm1 = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); {the .interval should be about 50, if it's high, the framerate will be low} private { Private declarations } public { Public declarations } end; TFadingMode=(fmFlash,fmPulse);{Two types of the effect.} var Form1: TForm1; Starting_Time:TDateTime; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin Starting_Time:=Now; end; function TimeElapsed(Since:TDateTime):integer; var h,m,s,ms:Word; begin DecodeTime(Now-Since,h,m,s,ms); Result:=m*60000+s*1000+ms; { It may be: Result:=h*3600000+m*60000+s*1000+ms; But not necessary. } end; procedure TForm1.Timer1Timer(Sender: TObject); const PulsingRate=500; FadingMode=fmPulse; {Modify these to get different results} var f:Byte; {the formula} begin case FadingMode of {fades from color1 to color2 then turns back to color1} fmFlash:f:=255*(TimeElapsed(Starting_Time) mod PulsingRate) div PulsingRate; {fades from color1 to color2 then fades back to color1} fmPulse:f:=255*Abs(TimeElapsed(Starting_Time) mod PulsingRate*2 - PulsingRate) div PulsingRate; end; {Then set the color with the RGB function} Canvas.Brush.Color:=RGB(f,0,0); { currently modifying RED, but you can get other colors like: RGB(f,0,0) - black-red RGB(255-f,0,0) - red-black RGB(0,f,0) - black-green RGB(50,150,f) - green-blue RGB(f,f,0) - yellow-black RGB(f,f,f) - white-black } {then do the job... paint something etc.} Canvas.Ellipse(50,50,150,150); end; end. It's good because you can refresh the screen anytimes, the result depends only on the time elapsed. You don't have to declare a lot of variables. And you can use the formula everywhere where is a color used. Just refresh it often!