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

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

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.

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:

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

Change the Grid’s background to LinearGradientBrush. In this case Grid is our root element. Create three rectangles inside the 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

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

This will generate the following Xaml behind the scenes, in the section:

Now change the to 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 to in the middle DoubleAnimationUsingKeyFrames section. Add the KeySpline property in and your code should look like this:

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.

is yet another Silverlight assembly with no direct counterpart in the full framework, but with tons of stuff inside (as evidenced by its size on disc and by the 21 namespaces!) that makes it the 2nd largest assembly. You can think of it as the brick that gives Silverlight its WPF UI. Its namespaces come from various v2.0 and v3.0 desktop assemblies as listed below (and it is in my opinion a prime candidate for refactoring):

- 2 of its namespaces (System.Windows.Ink, System.Windows.Media.Imaging) map to the desktop's PersentationCore.dll.

- System.Windows namespace has a total of 61 types, coming from homonymous namespaces in PresentationCore.dll (e.g. FontStyle, RoutedEventHandler) and PresentationFramework.dll (e.g. Application, FrameworkElement) and WindowsBase.dll (e.g. DependencyProperty, Point) and also introduces some new types (e.g. AssemblyPart, ErrorType).

- System.Windows.Markup namespace with 2 types from WindowsBase.dll, 2 from PresentationFramework.dll and 1 from PresentationCore.dll.

- System.Windows.Input largely maps to PresentationCore.dll, except for 2 classes (Key and ModifierKeys) from WindowsBase.dll and 1 class (KeyboardNavigationMode) from PresentationFramework.dll. There is also one new class in there: StylusInfo.

- System.Windows.Controls namespace has 24 types that come from PresentationFramework.dll (same namespace name of course). It also has 2 types (MultiScaleImage, MultiScaleSubImage) that make up the DeepZoom feature. It also has 3 types (2 from System.Windows.Forms.dll plus 1 brand new) that make up the OpenFileDialog feature.

- System.Windows.Interop namespace with 3 classes (Content, Settings and SilverlightHost) that is all new in Silverlight framework (even though that namespace name exists in various other WPF assemblies).

12. and 13.System.Windows.Controls.dll and System.Windows.Controls.Extended.dllThe overwhelming majority of the Silverlight controls reside in the System.Windows.Controls.dll assembly. The Extended.dll adds the Calendar, DatePicker, Slider and WatermarkedTextBox.

14. System.Windows.Controls.Data.dllThis adds a control not available at present in WPF: the Silverlight DataGrid. For all things DataGrid-related

(shows the DeepZoom feature in a public released site)2. Silverlight Airlines (gets you thinking of great user experience for booking a flight)3. Cameras (another example of great user experience for shopping online scenario)4. Image Snipper (shows graphics and interaction you would only expect from a desktop app)5. Video Puzzle (combination of a game with video elements)

...then before jumping into code, it is worth showing some of the controls that are available and also how they can be skinned (templated):6. Control Demo (not all of them, but gives you an idea)7. Corina's control skins Flat, Bubbly, Red, Rough.

Thursday, December 20, 2007

One of the nice features that Silverlight supports is the ability to go "full screen" and effectively take over the entire screen of a computer (hiding everything else from sight - including the browser frame). This can be very useful when building immersive UI experiences, games, rich video players, etc.For a nice example of this feature in action, make sure to check out the Fox Movies Sample on www.silverlight.net:

Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode). You can then hit the escape key to switch back into normal browser viewing.How to Implement Full Screen Mode with Silverlight 1.1 using .NETOne of the questions I've seen a few people ask is "how can you implement full screen-mode when building Silverlight applications using .NET?" The good news is that the answer is actually pretty easy:1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler). For security reasons Silverlight doesn't allow developers to switch an application into full-screen mode on first application load (you don't want an application to spoof you). So you'll instead need to trigger full-screen mode in response to a user action.2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace). This will cause Silverlight to switch into full screen mode. Setting this property to false will return it back to normal browser mode.Simple Full Screen Mode SampleYou can download a simple Silverlight full screen-mode sample I put together written in C# here. When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:

When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode. After a few seconds this message will disappear and only your content will be visible. In my sample above I also allow the user to click on the "Click to Return to Browser" text and switch back into browser mode as well.Walkthrough the Simple Full Screen Mode CodeThe code to implement the above sample is pretty simple. To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode. In the sample above I used a control that I named "MyMessage". Below is all of the XAML for the entire application:

Within the application's Page_Loaded() event handler above I am wiring up two event handlers: MyMessage_MouseLeftButtonDown - This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file. Within this event handler I'm simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode.BrowserHost_FullScreenChange - This event handler will execute anytime Silverlight switches between full screen and browser mode. It provides a good place to add logic to update the UI when this happens. In the example above I am changing the text on the TextBlock control. I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn't have layout manager support, so controls won't automatically re-position unless you write code to manage this yourself (don't worry - layout manager controls for Silverlight like in the desktop WPF version are coming). In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:

In this tutorial, I'm going to show you how to use Silverlight's Storyboard and ColorAnimation XAML tags to create custom color animations. Color animations are commonly used on input controls like buttons to give visual feedback that the cursor is over the control or when the button has been pressed. This tutorial will show a couple of simple examples that can easily be extended to complex controls and animations.

The examples in this post were built using Visual Studio 2008 beta 2, Silverlight 1.1 Alpha Refresh, and C#. For information on where to download these, please visit our previous tutorial Getting Started With Silverlight.

We'll start by defining the XAML for the rectangle.Here we've defined a very simple red rectangle. Since we want the color to change when the user enters or leaves the control with the cursor, we've defined event handlers for each of these. The code inside these event handlers is located in the C# code behind and will be explained a little later. Now that we have the rectangle defined, let's create an animation to change the color of the rectangle when the user enters it with the mouse cursor.The first thing you might notice here is the tag. This tag holds a collection of Storyboards and is located directly after the opening Canvas tag. Inside this tag is where we'll be placing the Storyboards that will control our color animations. The first Storyboard we're going to make will change the color of the rectangle when the user enters the control with the mouse. In order to control the Storyboard from the C# code-behind, you'll have to first give it a name. I named mine "mouseEnter". Next we add a ColorAnimation inside the Storyboard. The first attribute we set is Duration, which is how long the animation will run - in this case, 1 second. Next, we set the end result of the animation. I want my rectangle to fade from red to black, so I set To to "#000000". The next thing we set is the Storyboard.TargetName, which is the name of the object we want to modify. This has to be set to the same thing that we named the rectangle, in this case "myRectangle". Storyboard.TargetProperty is the property the animation will be changing, which in this case is the fill color. It might seem like a complicated way to address the rectangle's fill color, but it's necessary. If we expanded out the rectangle to use a SolidColorBrush it might make a little more sense:So in the attribute , "(Shape.Fill)" refers to and "(SolidColorBrush.Color)" is the Color attribute of . All right, the storyboard and animation are done and ready to be run. Let's create some C# code that will handle the events.private void MyRectangleMouseEnter(object sender, EventArgs e){ this.mouseEnter.Begin();}If you remember, we added a MouseEnter event to our XAML code and told it to execute the method MyRectangleMouseEnter. All this function does is to start the Storyboard we named "mouseEnter". If you build and preview your project, you should get something that looks like the following:If you ask me, that's not very interesting. Let's add in the XAML code to make the rectangle fade back to red when the mouse leaves the control.To make the rectangle fade back to red, I simply added another Storyboard to the canvas resources. The only thing different from the previous ColorAnimation is that To is now set to red (#FF0000), instead of black (#000000). Just like with the previous storyboard, we'll going to need some C# code to run the animation. This time, the function is hooked up to the rectangle's MouseLeave event.private void MyRectangleMouseLeave(object sender, EventArgs e){ this.mouseLeave.Begin();}That's it. Now we have a rectangle that fades to black when the mouse enters it and fades back to red when the mouse leaves.We've only barely touched the surface for the possibilities of what a color animation is capable of - but hopefully this tutorial will provide you with a launching point for your own complex (and much more interesting) animations.

Silverlight is a relatively new client side technology released by Microsoft, but already people are finding the need to communicate between their Silverlight applications and Javascript. This tutorial will go through all the code required to call Javascript functions from Silverlight and vice-versa.All the Silverlight code and examples were created using the 1.1 Alpha Refresh. Before you can use the example application below, you'll need to download the runtime (if you haven't already). If you're new to Silverlight, check out our introductory tutorial for information on what to download and how to get started.

Before we jump into code, let's look at an example of some communication between Silverlight and Javascript. The application on the left was created using Silverlight, the one on the right was made using HTML and CSS. When one of the buttons on the left is clicked, a message will be displayed on the right indicating that. The same thing happens when a button on the right is clicked.

So let's see how something like this is done. We'll start with the hard one - calling a Javascript function from Silverlight. There's no direct way (that I know of) to simply call a Javascript function directly from the Silverlight code behind. What we have to do is create events and attach to them from the Javascript code. This isn't a lot of work, but being able to call them directly would be a nice feature to have. So let's look at someC# code behind that creates the events.

using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Browser;namespace SilverlightJavascript{ [Scriptable] public partial class Page : Canvas { [Scriptable] public event EventHandler ButtonAClicked; [Scriptable] public event EventHandler ButtonBClicked; [Scriptable] public event EventHandler ButtonCClicked; public void Page_Loaded(object o, EventArgs e) { // Required to initialize variables InitializeComponent(); WebApplication.Current.RegisterScriptableObject( "SilverlightApp", this); } }}Since my Silverlight application has three buttons, I created three events - one for each button. They're created and used exactly like they are in an ordinary C# Windows application. One difference I'm sure you noticed is the [Scriptable] attribute above the definition of the class and each event. This lets Silverlight know that this class and these events should be accessible from the Javascript code. The next thing you might have noticed is the RegisterScriptableObject call. With this function we're telling Silverlight to make this class accessible via scripts by the name "SilverlightApp". Now whenever I want to use this object in Javascript, I'll reference it by the name "SilverlightApp". We'll see how this works later. Now that everything is setup, let's look at some C# code to fire our newly created events.

void ButtonA(object sender, MouseEventArgs e){ if (ButtonAClicked != null) ButtonAClicked(this, e);}void ButtonB(object sender, MouseEventArgs e){ if (ButtonBClicked != null) ButtonBClicked(this, e);}void ButtonC(object sender, MouseEventArgs e){ if (ButtonCClicked != null) ButtonCClicked(this, e);}In my XAML code I hooked up a MouseLeftButtonUp event to each of my buttons. Now when a button is clicked, one of these functions will be called. As you can see, firing the events is no different than a C# application. You should always make sure to check that an event is not null before firing it - otherwise things tend to crash. An event will be null if nothing has attached to it. That's all the code required on the Silverlight side to call Javascript functions. Now let's look at how to make Javascript listen for these events. The first thing we need to do is attach Javascript functions to each event. We'll do this as soon as the Silverlight application is done loading. So now you're probably wondering, how do we know when the Silverlight is done loading? There's an event we can listen for that is called as soon as it's finished. In order to get this event we need to modify the Javascript that Visual Studio generated as part of the test code. In my solution, the .js file is named TestPage.html.js. It might be different for you depending on how you set it up.

// JScript source code//contains calls to silverlight.js, example below loads Page.xamlfunction createSilverlight(){ Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById( "SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {onLoad: OnLoaded} }); // Give the keyboard focus to the Silverlight // control by default document.body.onload = function() { var silverlightControl = document.getElementById('SilverlightControl'); if (silverlightControl) silverlightControl.focus(); }}This should look very similar to what Visual Studio has created for you. The addition we have to make is in the events: {} section. We need to add an event for onLoad. With this addition, we're telling Silverlight to call the Javascript function OnLoaded as soon as it's finished loading. The OnLoaded function is where we're going to be attaching Javascript functions to our Silverlight events. So let's see how that's done.

function OnLoaded(sender, args){ sender.Content.SilverlightApp.ButtonAClicked = ButtonAClicked; sender.Content.SilverlightApp.ButtonBClicked = ButtonBClicked; sender.Content.SilverlightApp.ButtonCClicked = ButtonCClicked;}function ButtonAClicked(){ //The Silverlight A button has been clicked}function ButtonBClicked(){ //The Silverlight B button has been clicked }function ButtonCClicked(){//The Silverlight C button has been clicked}The OnLoaded event is automatically passed in the Silverlight object and some event arguments. Here's where we use the "SilverlightApp" name we created above. With those assignments, we're telling Silverlight to execute a Javascript function whenever one of those events is fired. So now, whenever the event ButtonAClicked is fired from the Silverlight Application, the Javascript function ButtonAClicked will be executed. That's it for calling Javascript functions from Silverlight. Now let's look at how to call Silverlight functions from Javascript. This process is much easier than calling Javascript from Silverlight. The first thing we need is a C# function we want called. Let's add one to our Silverlight code behind.

Scriptable]public void HTMLButtonAClicked(){ //The HTML A button has been clicked}There nothing special about this function except for the [Scriptable] attribute which makes it accessible by our Javascript code. All that's left is to call this function from the Javascript code.

As you can see, this is much easier than the other way around. The first thing we need to do is get the Silverlight object. You're probably wondering where the "SilverlightControl" id came from which is passed into getElementById. This is set back in the .js file that Visual Studio created for you. All that's left to do is access the class we named "SilverlightApp" and call the HTMLButtonAClicked function. Once that's done, the function we wrote in the C# code behind will be executed. I hoped you enjoyed this tutorial on Silverlight and Javascript interaction. Post a comment if you have any questions.