Delphi实例之绘制正弦函数图像
1 unit Unit1; 2 3 interface 4 5 uses 6 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 7 Dialogs, StdCtrls, ExtCtrls; 8 9 type 10 TForm1 = class(TForm) 11 Image1: TImage; 12 Button1: TButton; 13 Label1: TLabel; 14 Label2: TLabel; 15 Label3: TLabel; 16 Label4: TLabel; 17 Label5: TLabel; 18 Label6: TLabel; 19 procedure Button1Click(Sender: TObject); 20 private 21 { Private declarations } 22 public 23 { Public declarations } 24 end; 25 26 var 27 Form1: TForm1; 28 29 implementation 30 31 {$R *.dfm} 32 33 procedure TForm1.Button1Click(Sender: TObject); 34 var 35 x,l:Integer; 36 y,a:double; 37 begin 38 Image1.Picture.Bitmap:=TBitMap.Create; 39 Image1.Picture.Bitmap.Width:=Image1.Width; 40 Image1.Picture.Bitmap.Height:=Image1.Height; 41 l:=Image1.Picture.Bitmap.Width;
{下面的语句用于绘制直角坐标系} 42 Image1.Canvas.MoveTo(0,(Image1.Height div 2)); 43 Image1.Canvas.Pen.Color:=clBlue; 44 Image1.Canvas.LineTo(Image1.Width,(Image1.Height div 2));{绘制函数图像X轴} 45 Image1.Canvas.MoveTo((Image1.Width div 2),Image1.Height); 46 Image1.Canvas.LineTo((Image1.Width div 2),0);{绘制函数图像Y轴} 47 for x:=0 to l do 48 begin 49 a:=(x/l)*2*Pi;{角度化弧度} 50 y:=sin(2*a);{为了加强美观效果,这里讲振幅设为2} 51 y:=y*(Image1.Picture.Bitmap.Height/2); 52 y:=y+(Image1.Picture.Bitmap.Height/2); 53 Image1.Picture.Bitmap.Canvas.Brush.Style:=bsSolid; 54 Image1.Picture.Bitmap.Canvas.Pixels[Trunc(x),Trunc(y)]:=clRed;{当然也可以用LineTo过程来实现,但是要注意设置Pen.Width到合适的值} 55 end; 56 label1.Visible:=true; 57 Label2.Visible:=true; 58 label3.Visible:=true; 59 Label4.Visible:=true; 60 label5.Visible:=true; 61 Label6.Visible:=true; 62 end; 63 64 end.
注意,这里我用了四个标签,分别用于显示X,Y,0,f(x)=sinx,并事先将它们的Visible属性设为False,当图像绘制完成后在将Visible改为True。