Download DrawAnimatedImage.zip, last updated 28/10/2017 (567.26 KB)

Download
  • md5: 4a018e6a7814473a37471c9302ac242e
  • sha1: 9c32f16ee743d4338f2e61836b88f8efc3568514
  • sha256: aca4e0a6d1aa4ed63fadecbc6e60039f7249f89abf73555c011ac34c41535da7
// Painting animated images using C#
// http://www.cyotek.com/blog/painting-animated-images-using-csharp
// Copyright © 2017 Cyotek Ltd. All Rights Reserved.

// This work is licensed under the Creative Commons Attribution 4.0 International License.
// To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/.

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Cyotek.Demo.DrawAnimatedImage
{
  public partial class MainForm : Form
  {
    #region Fields

    private Image _image;

    private bool _isAnimating;

    #endregion

    #region Constructors

    public MainForm()
    {
      this.InitializeComponent();
    }

    #endregion

    #region Methods

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
      base.OnFormClosing(e);

      if (!e.Cancel)
      {
        this.CleanUp();
      }
    }

    protected override void OnShown(EventArgs e)
    {
      base.OnShown(e);

      this.OpenImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Newtons_cradle_animation_book_2.gif"));
    }

    private void CleanUp()
    {
      if (_image != null)
      {
        // disable animations
        if (_isAnimating)
        {
          ImageAnimator.StopAnimate(_image, this.OnFrameChangedHandler);
        }

        _isAnimating = false;

        _image.Dispose();
        _image = null;
      }
    }

    private void customPaintPanel_Paint(object sender, PaintEventArgs e)
    {
      if (_image != null)
      {
        int x;
        int y;
        int w;
        int h;
        Size clientSize;

        // update the image so that it will paint the current frame
        if (_isAnimating)
        {
          ImageAnimator.UpdateFrames(_image);
        }

        // determine the location of the image and then paint it
        clientSize = customPaintPanel.ClientSize;
        w = _image.Width;
        h = _image.Height;
        x = (clientSize.Width - w) / 2;
        y = (clientSize.Height - h) / 2;

        e.Graphics.DrawImage(_image, new Rectangle(x, y, w, h), new Rectangle(0, 0, w, h), GraphicsUnit.Pixel);
      }
    }

    /// <summary>
    /// Called when the animation frame changes.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="eventArgs">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void OnFrameChangedHandler(object sender, EventArgs eventArgs)
    {
      customPaintPanel.Invalidate();
    }

    private void OpenImage(string fileName)
    {
      if (!File.Exists(fileName))
      {
        MessageBox.Show(string.Format("Unable to open image, cannot find file '{0}'.", fileName), "Open Image", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
      }
      else
      {
        this.CleanUp();

        try
        {
          _image = Image.FromFile(fileName);

          this.SetupAnimation();

          customPaintPanel.Invalidate();
        }
        catch (Exception e)
        {
          MessageBox.Show(string.Format("Unable to open image. {0}", e.GetBaseException().Message), "Open Image", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
      }
    }

    private void openImageButton_Click(object sender, EventArgs e)
    {
      using (FileDialog dialog = new OpenFileDialog
                                 {
                                   Title = "Open Image",
                                   DefaultExt = "png",
                                   Filter = "All Pictures (*.emf;*.wmf;*.jpg;*.jpeg;*.jfif;*.jpe;*.png;*.bmp;*.dib;*.rle;*.gif;*.tif;*.tiff)|*.emf;*.wmf;*.jpg;*.jpeg;*.jfif;*.jpe;*.png;*.bmp;*.dib;*.rle;*.gif;*.tif;*.tiff|Windows Enhanced Metafile (*.emf)|*.emf|Windows Metafile (*.wmf)|*.wmf|JPEG File Interchange Format (*.jpg;*.jpeg;*.jfif;*.jpe)|*.jpg;*.jpeg;*.jfif;*.jpe|Portable Networks Graphic (*.png)|*.png|Windows Bitmap (*.bmp;*.dib;*.rle)|*.bmp;*.dib;*.rle|Graphics Interchange Format (*.gif)|*.gif|Tagged Image File Format (*.tif;*.tiff)|*.tif;*.tiff|All files (*.*)|*.*"
                                 })
      {
        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
          this.OpenImage(dialog.FileName);
        }
      }
    }

    private void SetupAnimation()
    {
      _isAnimating = ImageAnimator.CanAnimate(_image);

      if (_isAnimating)
      {
        ImageAnimator.Animate(_image, this.OnFrameChangedHandler);
      }

      statusLabel.Text = _isAnimating ? "Image is animated" : "Image does not support animation";
    }

    #endregion
  }
}

Donate

Donate