Click here to Skip to main content
15,894,405 members
Articles / Programming Languages / C#

Creating your own animation format

Rate me:
Please Sign up or sign in to vote.
4.96/5 (22 votes)
6 Feb 2013CPOL14 min read 36.7K   726   33  
Learn how to create your own animation format, capable of doing basic compression.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Globalization;
using System.IO;
using Pfz.Imaging;
using Pfz.Imaging.Wpf;
using System.Diagnostics;

namespace PfzImagingSample
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            _animation = _Animation();
            _eternalAnimation = _EternalAnimation();

            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0/30.0);
            timer.Tick += new EventHandler(timer_Tick);
            timer.IsEnabled = true;
        }

        private readonly IEnumerable<BitmapSource> _animation;
        private readonly IEnumerator<BitmapSource> _eternalAnimation;
        private void timer_Tick(object sender, EventArgs e)
        {
            _eternalAnimation.MoveNext();
            imageShowAnimation.Source = _eternalAnimation.Current;
        }

        private IEnumerator<BitmapSource> _EternalAnimation()
        {
            while(true)
                foreach(var frame in _animation)
                    yield return frame;
        }
        private IEnumerable<BitmapSource> _Animation()
        {
            BitmapSource background;
            using (var stream = File.OpenRead("Background.png"))
            {
                var pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                background = pngDecoder.Frames[0];
            }

            var rectangle = new Rect(0, 0, 300, 225);
            var formattedText = new FormattedText("Sample Animation", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal), 14, Brushes.Yellow);
            var target = new RenderTargetBitmap(300, 225, 96, 96, PixelFormats.Pbgra32);
            // The format should be Rgb24 but the RenderTargetBitmap does not support it.

            for (int frameIndex = 0; frameIndex < 90; frameIndex++)
            {
                int y = 255*frameIndex/90 - 10;
                var drawingVisual = new DrawingVisual();
                var context = drawingVisual.RenderOpen();

                if (checkboxUseBackgroundImage.IsChecked.GetValueOrDefault())
                    context.DrawImage(background, rectangle);
                else
                    context.DrawRectangle(Brushes.Black, null, rectangle);

                context.DrawText(formattedText, new Point(0, y));
                context.Close();

                target.Render(drawingVisual);

                yield return target;
            }
        }

        private void _SaveAnimation(IFrameWriter<Rgb24> frameWriter)
        {
            int factor = comboboxQuality.SelectedIndex + 1;

            if (factor > 1)
                frameWriter = new SimplifyBitmapWriter<Rgb24>(frameWriter, factor);

            bool requiresDifferentBitmap = frameWriter.RequiresDifferentBitmap;
            ManagedBitmap<Rgb24> bitmap = null;
            foreach (var frame in _animation)
            {
                var converted = new FormatConvertedBitmap(frame, PixelFormats.Rgb24, null, 1);

                if (bitmap == null || requiresDifferentBitmap)
                    bitmap = new ManagedBitmap<Rgb24>(converted.PixelWidth, converted.PixelHeight);

                converted.CopyPixels(bitmap);
                frameWriter.WriteFrame(bitmap);
            }

            Process.Start(".");
        }

        private void buttonSaveDeflateAnimation_Click(object sender, RoutedEventArgs e)
        {
            string fileName = string.Format("Animation_{0:yyyy_MM_dd-HH_mm_ss}.pdz", DateTime.Now);
            using (var stream = File.Create(fileName))
                using (var frameWriter = new DeflateFrameWriter<Rgb24>(stream))
                    _SaveAnimation(frameWriter);
        }

        private void buttonSavePngAnimation_Click(object sender, RoutedEventArgs e)
        {
            string directoryName = string.Format("Animation_{0:yyyy_MM_dd-HH_mm_ss}", DateTime.Now);
                using (var frameWriter = new MultiplePngRgb24FrameWriter(directoryName))
                    _SaveAnimation(frameWriter);

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Microsoft
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (in October 2014 I started working at Microsoft, so I can't be a Microsoft MVP anymore).

Comments and Discussions