Generating smooth animations with C# across different computer systems can be a challenging task. However there is a simple method to adjust a program behavior to a target number of frames per second.

Animating objects with C# can mean a number of different things.

First would be animating a sequence of picture images like an animated GIF. In this case there is already some existing support in the .Net Framework, but perhaps you want to handle drawing on a frame-by-frame basis.

Another form of animation is with code-generated images. GDI%2B can draw some very complex graphics and animating them smoothly can bring an extra dimension of quality to your .Net applications.

Lastly sometimes programmers want to animate Window Form behavior, such as size, position, text, etc. While these are object properties, we want them to change within a regular interval, no matter what the speed of the computer CPU is.

The first step for writing constant FPS animation in C# is to decide the way to measure CPU cycles. The most commonly used objects to measure time is the Timer object and the DateTime class. While both are easy to use, they lack accuracy. Instead, we are going to make use of the System.Diagonistics.StopWatch class.

The StopWatch class uses the API call QueryPerformanceTimer to keep track of CPU cycles, which is more accurate. Greater accuracy in this case means a more constant animation.

Basically you will want to keep track of three values, two of which will change constantly:

  • Interval = Stopwatch.Frequency / [target FPS (30.0 for example)]
  • currentTicks = Stopwatch.GetTimestamp()
  • lastTicks = same as currentTicks but taken the last time the animation was drawn

The logic behind the C# algorithm is not too complicated. In nutshell, a loop will be constantly running, but you only want the animation to execute/refresh when the last number of CPU cycles and the current number of cycles has at least a gap of the Interval you previously calculated. Then and only then is the animation refreshed.

The result is a constant animation no matter how fast a computer is. Simply adjust the FPS in your own system and that will be the perceived speed across systems.

The reason it works is because animations are not run on a simple while/for loop brainlessly. The loop uses the host computer’s CPU cycles to adjust the interval the animation is refreshed.

By arnia

Leave a Reply