delphi gif png bmp jeg 显示方法

/// <summary>
/// 注意不要忘记引用那几个图片单元哦,除了bmp格式不需要引用任何单元,
/// 其它图片格式都需要引用对应的图片单元
/// png ---> Vcl.Imaging.pngimage
/// jpg ---> Vcl.Imaging.jpeg
/// gif ---> Vcl.Imaging.GIFImg
/// </summary>
procedure TForm12.btn1Click(Sender: TObject);
var
  Rect1,Rect2: TRect;
  Picture: TPicture;
  op: TOpenDialog;
begin
  Picture := TPicture.Create;
  op := TOpenDialog.Create(nil);
  try
    if op.Execute then
    begin
      Picture.LoadFromFile(op.FileName);

      //---------------------------------------
      //如果是动态的gif图片,想让他动起来可以这样
      if ExtractFileExt(op.FileName) = '.gif' then
      begin
        //这句对Draw和StretchDraw 不生效,经过讨论可能是Draw 只画了GIF的第一帧,所以导致动画不会显示,这个暂时无解
        //用TImage来显示,动画就生效了。
        TGIFImage(Picture.Graphic).Animate := True;
      end;


      //---------------------------------------
      //画法1:最简单画法,但是无法控制图片的大小,就是说当图片很大的时候画出来会很大,
      //画出来的是原始图片没有缩放的大小
      //第一个参数是Left 第二个参数是 Top 就是开始画的位置
      Canvas.Draw(10,10, TGIFImage(Picture.Graphic));


      //---------------------------------------
      //画法2:设定一个矩形范围,把图片画到这个矩形中,但是注意Stretch这个单词,意思是
      //会伸缩图片 填充整个矩形区域,意味着图片会变形。不过一般变形还可以啊,保证图片人眼能
      //识别多好。
      Rect1.Left := 50;
      Rect1.Top := 50;
      Rect1.Width :=  200;
      Rect1.Height := 250;
      Canvas.StretchDraw(Rect1, Picture.Graphic);


      //---------------------------------------
      //画法3:画法2的扩展,按照矩形区域的长宽比例,来伸缩图片,保证伸缩的时候不变形,注意jpg
      //格式的图片是不允许修改图片的大小的,所以这种方法会不灵,这种方法仅作为参考吧。
      Rect2.Left := 300;
      Rect2.Top := 250;
      Rect2.Width :=  100;
      Rect2.Height := 300;
      //当图片的高度或宽度大于区域的时候才需要伸缩,其它情况不需要
      if Picture.Graphic.Width > Rect2.Width then
      begin
        Picture.Graphic.Width := Round(Picture.Graphic.Width * (Rect2.Width / Picture.Graphic.Width));
        Picture.Graphic.Height := Round(Picture.Graphic.Height * (Rect2.Width / Picture.Graphic.Width));
      end else if Picture.Graphic.Height > Rect2.Height then begin
        Picture.Graphic.Width := Round(Picture.Graphic.Width * (Rect2.Height / Picture.Graphic.Height));
        Picture.Graphic.Height := Round(Picture.Graphic.Height * (Rect2.Height / Picture.Graphic.Height));
      end;
      Canvas.Draw(Rect2.Left, Rect2.Top, Picture.Graphic);


      //---------------------------------------
      //显示方法4:当然是 TImage大哥了这个没啥说的,弄个Image控件来显示
      //Image1.Picture.LoadFromFile(op.FileName);
      Image1.Stretch := False;//这个来控制是否伸缩.
      Image1.Picture.Graphic := Picture.Graphic;//或这样
    end;
  finally
    Picture.Free;
    op.Free;
  end;
end;

发布了402 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_18932003/article/details/105122714
今日推荐