delphi 正弦曲线图
本实例要在窗体上直接绘制正弦曲线,为了防止窗口切换的过程中会输出不完整的图形,因此绘制图形的关键代码都放在了窗体的OnPaint过程中,代码如下:
procedure TForm1.FormPaint(Sender: TObject);
var
x: Integer;
y,a: Double;
begin
Canvas.Pen.Width:=3;
Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
for x := 0 to self.ClientWidth do
begin
a := (x/self.ClientWidth) * 2 * Pi;
y := Sin(a);
y := (1-y)*self.ClientHeight/2;
Canvas.LineTo(Trunc(x), Trunc(y));
end;
end;
程序首先设置了窗体的Canvas对象中画笔的宽度,并且把绘图的起点移动到了窗体中(0,Trunc(self.ClientHeight/2))的位置。然后通过一个循环中的a:= (x/self.ClientWidth)*2*Pi语句将一个正弦周期内的角度值转换为弧度值,并且把正弦计算后的结果存储在变量y中。最后,循环中的Canvas.LineTo(Trunc(x), Trunc(y))语句就会在窗体上绘制出连续的正弦曲线。
程序代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormPaint(Sender: TObject);
var
x: Integer;
y,a: Double;
begin
Canvas.Pen.Width:=3;
Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
for x := 0 to self.ClientWidth do
begin
a := (x/self.ClientWidth) * 2 * Pi;
y := Sin(a);
y := (1-y)*self.ClientHeight/2;
Canvas.LineTo(Trunc(x), Trunc(y));
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
Refresh;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
self.DoubleBuffered:=true;
//防止图形闪烁
end;
end.
保存文件,然后按F9键运行程序。在程序运行过程中,会自动在窗体上绘制正弦曲线,运行结果如图1所示。
图1 程序运行结果
通过本程序的学习,不但可以绘制正弦曲线,也可以绘制余弦曲线、正切曲线等各式各样的曲线,方便科学研