BLOG.CSHARPHELPER.COM: Animate a series of images in C#
Animate a series of images in C#
This example displays a series of images to make an animation. It loads the images at run time. To make finding the images easier, I added them to the project. (Open the Project menu, select Add Existing Item, and select the images.) I then selected the images in Solution Explorer and set their "Copy to Output Directory" properties to "Copy if newer" so they are copied into the executable directory. The program can then find them easily by specifying only the file names and not their paths.
The following code shows how the program loads the image files when it starts.
// The frame images.
private Bitmap[] Frames;
// The index of the current frame.
private int FrameNum = 0;
// Load the images.
private void Form1_Load(object sender, EventArgs e)
{
// Load the frames.
Frames = new Bitmap[18];
for (int i = 0; i < 18; i++)
{
Frames[i] = new Bitmap("Frame" + i + ".png");
}
// Display the first frame.
picFrame.Image = Frames[FrameNum];
}
The program stores the images in the Frames array. Initially it sets FrameNum to 0 so it displays the first frame.
When the form loads, the program loops from 0 to 17 loading image files with names of the form Frame0.png, Frame1.png, etc. The form's Load event handler finishes by displaying the first frame in the picFrame PictureBox.
The program's form contains a Timer that displays frames. The following code shows how the Timer's Tick event handler displays the next frame.
The code increments FrameNum and takes is modulo the number of frames. That makes FrameNum always represent a frame number between 0 and the largest index in the Frames array.
The event handler then displays the current frame in the picFrame PictureBox.
The program's Start button uses the following code to start or stop the Timer.
// Start or stop the animation.
private void btnStartStop_Click(object sender, EventArgs e)
{
tmrNextFrame.Enabled = !tmrNextFrame.Enabled;
if (tmrNextFrame.Enabled) btnStartStop.Text = "Stop";
else btnStartStop.Text = "Start";
}
The final piece of the program is its scroll bar named hscrFps. When you change the scroll bar's value, the following code changes the Timer's speed.
// Set the delay per frame.
private void hscrFps_Scroll(object sender, ScrollEventArgs e)
{
tmrNextFrame.Interval = 1000 / hscrFps.Value;
lblFps.Text = hscrFps.Value.ToString();
}
The only trick here is that the event handler converts the scroll bar's value in frames per second (fps) into milliseconds per frame as needed by the Timer. It also displays the frames per second value so the user can see it.
Comments