In this example, a sinusoidal curve is drawn directly on the form. In order to prevent incomplete graphics from being output during window switching, the key code for drawing graphics is placed in the OnPaint process of the form. The code is as follows:
procedureTForm1.FormPaint(Sender:TObject);
var
x:Integer;
y,a:Double;
begin
Canvas.Pen.Width:=3;
Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
forx:=0toself.ClientWidthdo
begin
a:=(x/self.ClientWidth)*2*Pi;
y:=Sin(a);
y:=(1-y)*self.ClientHeight/2;
Canvas.LineTo(Trunc(x),Trunc(y));
end;
end;
The program first sets the width of the brush in the Canvas object of the form, and moves the starting point of drawing to the position of (0,Trunc(self.ClientHeight/2)) in the form. Then convert the angle value within a sinusoidal period into a radian value through the a:=(x/self.ClientWidth)*2*Pi statement in a loop, and store the result of the sine calculation in the variable y. Finally, the Canvas.LineTo(Trunc(x),Trunc(y)) statement in the loop will draw a continuous sinusoidal curve on the form.
The program code is as follows:
unitUnit1;
interface
uses
Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,
Dialogs,ExtCtrls,StdCtrls;
type
TForm1=class(TForm)
procedureFormPaint(Sender:TObject);
procedureFormResize(Sender:TObject);
procedureFormCreate(Sender:TObject);
private
{Privatedeclarations}
public
{Publicdeclarations}
end;
var
Form1:TForm1;
implementation
{$R*.dfm}
procedureTForm1.FormPaint(Sender:TObject);
var
x:Integer;
y,a:Double;
begin
Canvas.Pen.Width:=3;
Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
forx:=0toself.ClientWidthdo
begin
a:=(x/self.ClientWidth)*2*Pi;
y:=Sin(a);
y:=(1-y)*self.ClientHeight/2;
Canvas.LineTo(Trunc(x),Trunc(y));
end;
end;
procedureTForm1.FormResize(Sender:TObject);
begin
Refresh;
end;
procedureTForm1.FormCreate(Sender:TObject);
begin
self.DoubleBuffered:=true;
//Prevent graphics from flickering
end;
end.
Save the file and press F9 to run the program. During the running of the program, a sinusoidal curve will be automatically drawn on the form, and the running results are shown in Figure 1.
Figure 1 Program running results
By learning this program, you can not only draw sine curves, but also various curves such as cosine curves and tangent curves to facilitate scientific research.