Delphi自绘网格坐标系正弦波演示

procedure TForm1.Button1Click(Sender: TObject);
var
  x, l,i,j: Integer;
  y, a: double;
begin
  Image1.Picture.Bitmap := TBitMap.Create;
  Image1.Picture.Bitmap.Width := Image1.Width;
  Image1.Picture.Bitmap.Height := Image1.Height;
  l := Image1.Picture.Bitmap.Width;

  for x := 0 to l do
  begin
    a := (x / l) * 2 * Pi; {角度化弧度}
    y := sin(2 * a); {为了加强美观效果,这里将振幅设为2}
    y := y * (Image1.Picture.Bitmap.Height / 2);
    y := y + (Image1.Picture.Bitmap.Height / 2);
    Image1.Picture.Bitmap.Canvas.Brush.Style := bsSolid;
    Image1.Picture.Bitmap.Canvas.Pixels[Trunc(x), Trunc(y)] := clRed; {当然也可以用LineTo过程来实现,但是要注意设置Pen.Width到合适的值}
  end;

// 绘制直角坐标系上显示的字符
  with Image1.Canvas do
  begin
    Font.Name    := 'Symbol';
    Font.Size    := 8;
    Font.Color   := clBlack;
    TextOut(2,Image1.Height div 2+1, '-2p');
    TextOut(Image1.Width div 4,Image1.Height div 2+1, '-p');
    TextOut(Image1.Width-20,Image1.Height div 2+1, '2p');
    TextOut(Image1.Width div 2+(Image1.Width div 4),Image1.Height div 2+1, 'p');
    TextOut(Image1.Width div 2+5,0, '2');
    TextOut(Image1.Width div 2+5,Image1.Height div 4+1, '1');
    TextOut(Image1.Width div 2+2,Image1.Height-12, '-2');
    TextOut(Image1.Width div 2+2,Image1.Height div 2+Image1.Height div 4-12, '-1');
  end;


  //画竖网格线
   j:=0;
  for I := 0 to Image1.Width div 15 do
  begin
    with Image1.Canvas do
    begin
      Pen.Color := clLtGray;
      Brush.Style := bsSolid;
      MoveTo(j,0 );
      LineTo(j,Image1.Height);
      {画上坐标数字}
     // TextOut(j-5,Image1.Height-13, IntToStr(i));
    end;
    Form1.Canvas.TextOut(Image1.Left+j-5,Image1.Top+Image1.Height+5, IntToStr(i));   {把坐标数字画到窗体上相应位置,以免影响正弦波显示}
    Inc(j,15);
  end;
   //画横网格线
   j:=15;
  for I := 0 to Image1.Height div 15 do
  begin
    with Image1.Canvas do
    begin
      Pen.Color := clLtGray;
      Brush.Style := bsSolid;
      MoveTo(0,j );
      LineTo(Image1.Width,j);
    end;
    Form1.Canvas.TextOut(Image1.Left-15,Image1.Top+j-8, IntToStr(i+1));   {把坐标数字画到窗体上相应位置}
    Inc(j,15);
  end;

  {下面的语句用于绘制直角坐标系x,y轴,后画x,y axis的原因是部分线条会被画网格线条覆盖}
  Image1.Canvas.MoveTo(0, (Image1.Height div 2));
  Image1.Canvas.Pen.Color := clBlue;
  Image1.Canvas.LineTo(Image1.Width, (Image1.Height div 2)); {绘制函数图像X轴}
  Image1.Canvas.MoveTo((Image1.Width div 2), Image1.Height); {留下底部15像素做为坐标文字位置 }
  Image1.Canvas.LineTo((Image1.Width div 2), 0); {绘制函数图像Y轴}

end;

效果截图

posted @ 2022-10-04 00:15  IT情深  阅读(92)  评论(0编辑  收藏  举报