Animated Gifs in .NET


I hadn’t noticed that the graphic classes in .NET had built-in support for animated gifs, but a recent GDN post shows how you can grab the individual frames out of a GIF and display them one at a time… I think you would have to find out the intended delay between frames to produce the author’s desired result, but I’m not positive as it has been awhile since I made an animated gif 🙂

http://www.gotdotnet.com/Community/MessageBoard/Thread.aspx?id=180291

Comments (4)

  1. Chris Sells says:

    Windows Forms has built-in support for GIF animation via the ImageAnimator class, e.g.

    // Load animated GIF

    Bitmap gif = new Bitmap(@"C:SAMPLE_ANIMATION_COPY.GIF");

    void AnimationForm_Load(object sender, EventArgs e) {

    // Check if image supports animation

    if( ImageAnimator.CanAnimate(gif) ) {

    // Subscribe to event indicating the next frame should be shown

    ImageAnimator.Animate(gif, new EventHandler(gif_FrameChanged));

    }

    }

    void gif_FrameChanged(object sender, EventArgs e) {

    if( this.InvokeRequired ) {

    // Transition from worker thread to UI thread

    this.BeginInvoke(

    new EventHandler(gif_FrameChanged),

    new object[] { sender, e });

    }

    else {

    // Trigger Paint event to draw next frame

    this.Invalidate();

    }

    }

    void AnimationForm_Paint(object sender, PaintEventArgs e) {

    // Update image’s active frame

    ImageAnimator.UpdateFrames(gif);

    // Draw image’s current frame

    Graphics g = e.Graphics;

    g.DrawImage(gif, this.ClientRectangle);

    }

    This is covered in Chapter 4 of Windows Forms Programming: http://sellsbrothers.com/writing/wfbook

  2. I authored the post at GDN which responded to the requestor’s requirement for VB.NET code that could play a GIF one time then stop.

    The frame delay times (in hundredths of a second) are stored in an GIF file and can be extracted and used with a timer to delay each frame correctly – as opposed to the hack I did with Thread.Sleep.

    The gif.GetPropertyItem(PropertyTagFrameDelay)method is used to get at the frame delay data in the gif.

    The PropertyTagFrameDelay PropertyItem’s Value property contains an array of bytes representing the delays between the frames in the animated GIF.

  3. Rama says:

    Duh!

    Just Place the Animated Gif in a picturebox on the form and let it handle all the animation – automatically!

  4. Mike McIntyre says:

    Rama,

    The request was to play the animation exactly one time then stop.

    Placed in a PictureBox this control is not possible.

    Mike