Search code examples
delphidelphi-2010

how to display an animated gif in Delphi 2010


I have tried each of the following in Delphi 2010 to display an animated gif on my form. All result in an access violation. (Two of the three variations were commented out on each attempt.) Thanks much.

uses
  ... GIFImg,...

Image1: TImage;

procedure TForm1.FormCreate(Sender: TObject);
begin
  // A valid animated gif was loaded into Image1 at design time
  TGIFImage(image1).Animate := true;
  TGIFImage(image1.Picture).Animate := true;
  TGIFImage(image1.Picture.Graphic).Animate := true;
end;

I attempted to follow the answer in the question linked above, but the solution did not work for me (and with that question being tagged explicitly as Delphi-7, I didn't know if something had changed). Rewriting to "(image1.Picture.Graphic as TGIFImage).Animate := true;" results in "... exception class EInvalidCast with message 'Invalid class typecast'." It's not clear to me why the typecast is invalid since I'm positive that an animated gif has already been loaded at design time.

Edit to clarify the issue, here's the revised code. The showmessage tells me that the image is a TdxSmartImage. No idea why it thinks this. (I did at one point try to load the image into a devExpress control to see if that would work, but I subsequently removed all dexExpress elements from the form/project and regenerated the gif file.

procedure TForm1.FormCreate(Sender: TObject);
begin
  image1.Picture.LoadFromFile('C:\ChronSource\ChronDialogs\11.0 job menu.gif');
  ShowMessage(image1.Picture.Graphic.ClassName);
  // this says "TdxSmartImage"
  (image1.Picture.Graphic as TGIFImage).Animate := true;
end;

Solution

  • Using the various responses above, I was able to come up with this approach that worked;

    procedure TForm1.FormCreate(Sender: TObject);
      var
        aGIF:TGIFImage;
        sFile: string;
    begin
      try
        ...
        aGIF := TGIFImage.Create;
        aGIF.LoadFromFile(sfile);
        aGIF.Animate := true;
        image1.Picture.Graphic := aGIF;
      except
      ...