C# Programming > Drawing GDI+

C# Displaying Animated GIF

The Code - An Animated GIF Class

Let's apply all of the concepts into one easy-to-use C# class:

public class GifImage
{
     private Image gifImage;
     private FrameDimension dimension;
     private int frameCount;
     private int currentFrame;
     private bool reverse;
     private int step = 1;

public GifImage(string path) { gifImage = Image.FromFile(path); //initialize dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); //gets the GUID frameCount = gifImage.GetFrameCount(dimension); //total frames in the animation }

public bool ReverseAtEnd //whether the gif should play backwards when it reaches the end { get { return reverse; } set { reverse = value; } }

public Image GetNextFrame() {
currentFrame += step;

//if the animation reaches a boundary... if (currentFrame >= frameCount || currentFrame < 1) { if (reverse) { step *= -1; //...reverse the count currentFrame += step; //apply it } else currentFrame = 0; //...or start over } return GetFrame(currentFrame); }

public Image GetFrame(int index) { gifImage.SelectActiveFrame(dimension, index); //find the frame return (Image)gifImage.Clone(); //return a copy of it } }

Conclusion

There are a few things to keep in mind. The SelectActivateFrame C# function modifies the same Image object, in which case you need to call the Clone() method before returning the new frame.

The above C# class for displaying animated GIFs also shows a small sample of the possibities of manually extracting frames from a GIF. One being that the frames are displayed backwards when the animation reaches the end. The GetFrame C# function allows direct access to any frame, which opens to door to custom FPS (frames per second) display...

Back to Page 1 - C# Display Animated GIF

Back to C# Article List

License Agreement | Privacy Policy | Submit Link | Submit Article | Subscribe to Newsletter | Contact Us