Published: 09 May 2008
By: Faisal Khan
Download Sample Code

In-Depth analysis of animation with Silverlight 2.0 Beta.

Contents [hide]

Introduction to Animation in Silverlight

Animation allows us to create attractive user interfaces. Animation is used to apply dazzling effects such as spin a logo or video, make text scroll, make images grow when the mouse is over them etc. Animation is much like varying the property value over time as far as Silverlight 2.0 is concerned. This will be clear if someone takes a closer look at the animated stuff done in Silverlight/WPF applications. For example, it is possible to make an element grow by increasing its Width and Height or changing its Color value or its opacity in a specified duration.

The Size, Color and Value of an element can be varied over a period of time by setting the duration in the Storyboard. Storyboard controls animations with a timeline, and provides object and property targeting information for its child animations. The real definition of animation is - "An illusion that is created by quickly cycling through a series of images". Our brain perceives the group of images as a single changing scene. In Television broadcast or Film this illusion is created using cameras that record a number of pictures - frames - each slightly different from the last displayed, in a specific amount of time by capturing them in a timeline.

Silverlight too has its timeline to specify what actions to perform at specified time intervals. In Silverlight all animations inherit from the Timeline object; therefore all animations are specialized type of Timelines. A timeline represents a segment of time. To specify the length of the segment, when it should start and stop, how many times it will repeat, how fast time progresses in that segment, Silverlight uses Timelines.

Before digging deep into animation, here are two sample programs to give you an idea on what animations do in Silverlight, or what can be done with animations. This is just a simple animated sample to show you the animation in action. You can modify this code to make it more effective. The sample program below animates two videos one after another:

Figure 1: Silverlight Animation in Action

Silverlight Animation in Action

The above is the first video in this application, which has been scaled, translated and rotated to get the animated effect. After this video finishes another one starts by spinnig over the first video. Check the picture of this animation:

Figure 2: The second animation in action

The second animation in action

You should be excited by now seeing the power of Silverlight animation. This application contains three MediaElements. Two of them have been animated and I have used the other for a five seconds video which shows the text “Powered by Silverlight” together with the Silverlight logo. The complete code is shown below, but don’t dig deeper into this before learning the basics, which will come next in this article.

Listing 1: Page.xaml

Listing 2: Page.xaml.cs

I’m not explaining this code here because earlier I’ve suggested you to take a look at the basics of the animation, before digging into this. You’ll see more in the video animation section of this article.

Animation types

Silverlight provides two types of animation:

  • From/To/By animations.
  • key-frame animations.

Classes that are derived from Timeline provide animation functionality. Here's the inheritance hierarchy:

  • System.Object
  • System.Windows.DependencyObject
  • System.Windows.Media.Animation.Timeline
  • System.Windows.Media.Animation.ColorAnimation
  • System.Windows.Media.animation.ColorAnimation.ColorAnimationUsingKeyFrames
  • System.Windows.Media.Animation.DoubleAnimation
  • System.Windows.Media.Animation.DoubleAnimationUsingKeyFrames
  • System.Windows.Media.Animation.ObjectAnimationUsingKeyFrames
  • System.Windows.Media.Animation.PointAnimation
  • System.Windows.Media.Animation.PointAnimationUsingKeyFrames
  • System.Windows.Media.Animation.Storyboard

When using animations, several of the following properties are needed:

  • AutoReverse: Reverses the animation if it has ended (i.e., moves the element back to where it started).
  • Duration: The duration of an animation, using the syntax hh:mm:ss (hours, minutes, seconds).
  • From: The start value for the animation.
  • To: The end value for the animation.
  • By: A relative value indicating by how much to change the animation (an alternative approach for using To).
  • RepeatBehavior: What to do if the animation has ended; you can provide a (total) duration, a number of times to repeat, or mark it Forever if the animation should repeat endlessly.
  • Storyboard.TargetName: The name of the element that needs to be animated (therefore, we needed to assign a name).
  • Storyboard.TargetProperty: The property of the element that needs to be animated.

To programmatically control the animation, the following methods are used:

  • Begin: Initiates the Storyboard.
  • Pause: Pauses the Storyboard.
  • Resume: Resumes a paused Storyboard.
  • Stop: Stops the Storyboard.
  • Seek: Skips to a specific part of the Storyboard animation.

A key-frame animation animates between a series of values specified using key-frame objects. Key-frame animations are more powerful than From/To/By animations because any number of target values can be specified and we can even control their interpolation method. We’ll see the power of key-frame animation in a moment.

ColorAnimationUsingKeyFrames animates the color of a SolidColorBrush or GradientBrush, DoubleAnimationUsingKeyFrames animates the width and height of FrameworkElements, PointAnimationUsingKeyFrames animates the center position of an EllipseGeometry, ObjectAnimationUsingKeyFrames animates the Fill property from one GradientBrush to another.

In key-fame animations a certain stage in the application must be reached. For example, an object needs to have specific positions. When a key-frame is reached a certain object value must be met. Every key frame needs at least two values or attributes:

  • KeyTime: At what time the key-frame will come into effect.
  • Value: The value that needs to be reached at a given time.

In a Timeline where you have a keyframe after half second with a value of 20, and another one after 1 and half seconds with value of 40, the assigned value of these two frames will be animated between them. How this value is animated from 20 to 40 will be defined by the second keyframe. There are different ways to interpolate the value, and the second keyframe needs to confirm which of these methods is used. Silverlight currently supports three methods: Linear, Discrete and Spline. Here’s an example of key frame animation. This example uses three rectangles to demonstrate Spline, Discrete and Linear key-frames. To create it, open Microsoft Expression Blend 2.5 March Preview.

Figure 3: Opening Expression Blend

Opening Expression Blend

Change the Grid’s background to LinearGradientBrush. In this case Grid is our root element. Create three rectangles inside the <Grid> section. Change also the background of the rectangles to LinearGradientBrush. By now, you should have change your visual interface to something like the following.

Figure 4: Visual Interface for Silverlight KeyFrameAnimations

Visual Interface for Silverlight KeyFrameAnimations

Add a Storyboard by clicking the + button which resides under the objects and timeline tab. Select rectangle1 in the Objects and Timeline panel. Translate the x property to 50 when Playhead position is in 0:00.000. Again translate the x property to 544 and the Playhead position will be in 0:01.000. At last set the x property to 0 again when the Playhead position is 0:03.000. Now select rectangle2, move the timeline where Playhead position is 0:00.300 and translate the x property of the TranslateTransform that will be applied to our second rectangle. Set the x value to 544 when the Playhead position is 0:01.000 and set it to 0 when Playhead position is 0:03.000. Do the same for the rectangle3. After completing this step you should have a timeline like the following.

Figure 5: KeyFrameAnimations Timeline

KeyFrameAnimations Timeline

This will generate the following Xaml behind the scenes, in the <Usercontrol.Resources> section:

Listing 3: Page.xaml

Now change the <SplineDoubleKeyFrame> to <DiscreteDoubleKeyFrame> in the last section of the DoubleAnimationUsingKeyFrames. Discrete key frames, like DiscreteDoubleKeyFrame, create sudden jumps between values. For example, if the rectangle is at the starting position, it can suddenly appear at the 500 position. The animated property won’t change until the key frame's key time is reached, at which point the animated property goes suddenly to the target value.

Change the <SplineDoubleKeyFrame> to <LinearDoubleKeyFrame> in the middle DoubleAnimationUsingKeyFrames section. Add the KeySpline property in <SplineDoubleKeyFrameSection> and your code should look like this:

Run the application and check the difference between them.

Principles of animation

Here I’m going to present the principles of animation extracted from the book MS Expression Blend Bible. It’s quite an effective concept to bring liveliness to your animated application.

Adding realism is a key factor when creating an eye catching animation. To me, as a developer of Silverlight applications, everyone should follow the principles of animation to add realism and effectiveness when applying animation to their application. As far as storytelling is concerned animation, for example when developing a game your animation may proceed like this:

  • Creating a script for storyboard.
  • Record voices, Sound effects and background music, and layer them together to create a soundtrack.
  • Designing visuals in more detail.
  • Animate those visuals.

If someone wants to put emphasis on adding interest and realism behind animation, the following principles should be kept in mind:

Squash and stretch

When an object is squashed, its volume should remain equal to the volume it has when it is not squashed. Squashing and stretching a bouncing ball can add realism, appeal or both. When two objects bump together, they both squash inward at the point of impact and stretch in a perpendicular direction, unless they are made of a completely rigid material. Then they regain their original shape. It’s important as an animator to always give the squashed and stretched shape the same volume as the original shape. The object shouldn’t appear to gain any mass.

Timing and motion

This is where user’s attentions are attracted and gives sense of weight, importance and anticipation to an object. Timing and motion are an integral part of every animation. Timing and motion can give a sense of the weight of an object. When an object takes a long time to get going and to stop, it gives the impression that it’s heavier than something that takes less time. User's attention can be attracted using motion in two ways: A moving object or character can attract the attention if everything else in the scene is still and a still object can attract attention if everything else in the scene is moving.

Staging

Plays the big part when the attention of the audience to the area of the screen containing the information is purposely brought. In animation, staging is the process by which the eye is drawn to the part of the screen that the animator wants to emphasize. For example, if a character lifts an eyebrow to indicate that he’s got a plan, you may want to show the action in a close-up so that the audience notices it.

Overlapping action and follow-through

It's handy when motion is given a practical or appearance of reality. Starting one action before another action is complete. Action that continues to occur after an action has mostly completed. For example, follow-through occurs when a ball is caught by a hand and the hand moves back to indicate that the ball pushed the hand back. Or when a walking character takes a step and his hand continues to swing.

Arcs

Animating motions along arcs, because most objects in nature don't move along a perfect straight line, this is when arcs are animated along motions. In the natural world, living things usually don’t move in straight lines. When we walk, we move up and down in an arc as we take a step, then straighten up and take the next. All animals move in an arc motion, some more than others. And the trees move with the wind in an arc. Arcs occur both visually and in time. Water in a stream is sometimes slow, sometimes fast. Wind blows, and then diminishes. Rabbits hop, and then stop. Varying the timing and the visual motion of your animation in a natural way can enhance the feeling that you may want it to convey.

These are the elements of animation that must be structured in an organized way in order to give attractiveness and realism no matter what platforms you are working on.

Summary

In the first part of this series we presented the main concepts of animations with Silverlight. We talked about animation types and discussed the key animation principles that you must keep in mind when developing rich applications. In the next part, we’ll dive deep into Storyboards.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Faisal Khan

Currently working at Vectorform as a Silverlight developer. His passions revolve around creating the next generation desktop application and Rich Internet applications. His goals are to create applications which will serve the user in a friendly and traditional way, but will keep pace with next ge...

This author has published 11 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


WPF Tutorial
With all the new technology that Microsoft is releasing, it's hard to keep up. WPF is one such techn...
Silverlight "WPF/E" first steps: Getting started with simple analog clock
This article is an introductory article on how to build a WPF/E simple web application that represen...
Introduction to XAML Part 1
You are coding in .NET and have basic knowledge of XML. You heard about that Windows Presentation F...
RIA Services With Silverlight 3 - Part 1
What RIA services actually are and how to use them with Silverlight.
Silverlight 3 and the Data Form Control—part I
Dino will briefly go through some patterns that help organizing the presentation layer and then focu...

You might also be interested in the following related blog posts


API changes introduced by the new CoverFlow control read more
Silverlight MVP read more
Watch out the flow is coming! Telerik CoverFlow for Silverlight 3 read more
Welcome the Free Test Automation Solution for RadControls read more
Telerik Launches RadControls for Silverlight 3 for Line-of-Business Application Development read more
Detecting Design Mode in Silverlight read more
Telerik Announces Support for Microsoft Silverlight 3 read more
Why Embedded Silverlight Makes Sense read more
Q3 2009 betas available now, Official release soon (update) read more
Silverlight 2 Animation Book Review read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Missing Code!!! Kazi Manzur Rashid 5/10/2008 2:54 AM
RE: Missing Code!!! Faisal Khan 5/13/2008 1:21 PM
placeholder Congrats Kazi Manzur Rashid 5/10/2008 2:54 AM
Video Sonu Kapoor 5/12/2008 10:17 PM
placeholder Can I translate this article into Chinese? Qingshan Yin 5/25/2008 10:31 PM
RE: Can I translate this article into Chinese? Faisal Khan 5/26/2008 8:17 AM

Please login to rate or to leave a comment.