Handling Animated GIFs

vckicks 0 Tallied Votes 234 Views Share

Draw animated GIFs in C# in a frame-by-frame basis. Gives you a finer level of control.

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
     }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.