WPF/XAML: Saving an animation as an AVI video file
In my previous post, I showed how to save a window or canvas as a PNG bitmap file. In this post I’m going to show how to save the animation in a Canvas as an AVI file.
First, add some animation.
var anim = new System.Windows.Media.Animation.DoubleAnimation(50, 400, TimeSpan.FromSeconds(10), System.Windows.Media.Animation.FillBehavior.HoldEnd);
var clock = anim.CreateClock();
this.ellipse1.ApplyAnimationClock(Canvas.LeftProperty,clock);
clock.Controller.Pause();
Then save each frame as a PNG and stuff it into an AVI
This uses the AviFile code from “A Simple C# Wrapper for the AviFile Library” on CodeProject.
int dpi = 96;
int fps = 24;
int anim_length_in_secs = 5;
int num_total_frames = fps*anim_length_in_secs;
var secs = Enumerable.Range(0, num_total_frames).Select(t => (((double)t) / fps));
var aviManager = new AviFile.AviManager(filename, false);
AviFile.VideoStream aviStream = null;
foreach (var sec in secs)
{
clock.Controller.SeekAlignedToLastTick(TimeSpan.FromSeconds(sec),
System.Windows.Media.Animation.TimeSeekOrigin.BeginTime);
this.canvas1.UpdateLayout();
string temp_bitmap = "d:\\canvas_frame.png";
util.SaveCanvas(this, this.canvas1, dpi, temp_bitmap);
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(temp_bitmap);
if (aviStream == null)
{
aviStream = aviManager.AddVideoStream(compress, fps, bm);
}
else
{
aviStream.AddFrame(bm);
}
bm.Dispose();
}
aviManager.Close();
The sample application
The source code is attached.
Clicking Save Animation will create a file called “d:\canvas.avi” which will show the large ellipse moving from the left to the right.