Animation in Silverlight 4

Exclusive offer: get 50% off this eBook here
Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide — Save 50%

Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook

$32.99    $16.50
by Frank LaVigne | April 2010 | Beginner's Guides Microsoft Web Development Web Graphics & Video

Packt are due to launch a new Enterprise brand, into which future Silverlight titles will be published. For more information on that launch, look here.

In this article by Frank LaVigne, author of Microsoft Silverlight 4 Business Application Development, we shall create an interactive logo using Silverlight and incorporate it into the website.

Silverlight sports a rich animation system that is surprisingly easy to use. The animation model in Silverlight is time based, meaning that movements occur based on a set timeline. At the heart of every animation is a StoryBoard, which contains all the animation data and independent timeline. Silverlight controls can contain any number of Storyboards.

StoryBoards contain one or more Key frame elements, which are responsible for making objects on screen change position, color, or any number of properties. There are four general types of Key frames in Silverlight 4: Linear, Discrete, Spline, and Easing. The table below illustrates what each one does:

Very different than Flash
The animation model in Silverlight is markedly different than the one found in Adobe Flash. Animations in Flash are frame-based, whereas in Silverlight they are time-based. The term StoryBoard comes from the motion picture industry, where scenes are drawn out before they are filmed.

Time for action – animation time

The client would like to transform their text-only logo into something a little more elaborate. The designers have once again given us a XAML snippet of code exported from their graphic design tool. We will need to do the following:

  1. Open up the CakeORama logo project in Blend.
  2. Blend should have automatically loaded the MainControl.xaml file and your screen should look like this:
  3. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  4. In the Objects and Timeline tab, you'll see a list of objects that make up this vector drawing. There is Path object for every character.
  5. Let's add an animation. On the Object and Timeline tab, click the plus sign (+) to create a new StoryBoard.
  6. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  7. In the Create Storyboard Resource dialog, type introAnimationStoryboard into the text box and click OK.
  8. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  9. You'll notice a couple of changes to your screen. For one, the art board is surrounded by a red border and a notification that: intoAnimationStoryboard timeline recording is on just like in this screenshot:
  10. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  11. If you take a look at the Objects and Timeline tab, you'll see the timeline for our newly created introAnimationStoryboard:
  12. Let's add a key frame at the very beginning. The vertical yellow line is the play head, which marks where you currently are in the timeline. Select the canvas1 object.
  13. You can switch to the Animation Workspace in Blend by pressing F6.

  14. Click on the square icon with a green plus sign to create a new Key frame here at position 0. A white oval appears representing the Key frame that you just created. It should look similar to the following screenshot:
  15. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  16. Move the play head to 0.7 seconds, by clicking on the tick mark to the immediate left of the number 1.
  17. Click the same button you did in step 9 to create a new key frame here so that your timeline looks like this:
  18. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  19. Move the play head back to zero.
  20. Make sure the canvas1 object is still selected, click and drag the logo graphic up, so that all of it is in the grey area. This moves the logo "off stage".
  21. Hit the play button highlighted in the below screenshot, to preview the animation and enjoy the show!
  22. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  23. Now all we need to do is tell Silverlight to run the animation when our control loads, but first we need to get out of recording mode. To do this, click the x button on the Objects and Timeline tab.
  24. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  25. Click on [UserControl] in the Objects and Timeline tab.
  26. On the Properties tab, you'll see an icon with a lightning bolt on it. Click on it to see the events associated with a UserControl object:
  27. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  28. To wire up an event handler for the Loaded event, type UserControl_Loaded in the text box next to Loaded, as shown in the next screenshot:
  29. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  30. Once you hit Enter, the code behind will immediately pop up with your cursor inside the event handler method.
  31. Add this line of code to the method:

introAnimationStoryboard.Begin();

Run the solution via the menu bar or by pressing F5. You should see the logo graphic smoothly and evenly animate into view. If for some reason the animation doesn't get displayed, refresh the page in your browser. You should see it now.

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

What just happened?

You just created your first animation in Silverlight. First you created a Storyboard and then added a couple of Key frames. You changed the properties of the canvas on one key frame and Silverlight automatically interpolated them in between points to create a nice smooth animation. If your animation didn't show up on the initial page load but did when you reloaded the page, then you've just experienced how seriously the Silverlight animation engine respects time. Since our animation length is relatively short (0.7 seconds) it's possible that more than that amount of time elapsed from the call of the Begin method, to the amount of time it took for your computer to render it. Silverlight noticed that and "jumped" ahead to that part of the timeline to keep everything on schedule.

Just like we did before, let's take a look at the XAML to get a better feel of what's really going on. You'll find the Storyboard XAML in the UserControl.Resources section towards the top of the document. Don't worry if the values are slightly different in your project:

<Storyboard x:Name="introAnimationStoryboard">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.
TargetName="canvas1" Storyboard.TargetProperty="(UIElement.Render
Transform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
<EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/>
<EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.
TargetName="canvas1" Storyboard.TargetProperty="(UIElement.Render
Transform).(TransformGroup.Children)[3].(TranslateTransform.X)">
<EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
<EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>

There are a couple of things going on here, so let's dissect the animation XAML starting with the Storyboard declaration which creates a Storyboard and assigns the name we gave it in the dialog box:

<Storyboard x:Name="introAnimationStoryboard">

That's easy enough, but what about the next node? This line tells the Storyboard that we will be modifying a Double value starting at 0 seconds. It also further specifies a target for our animation: canvas1 and a property on our target:

<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.
TargetName="canvas1" Storyboard.TargetProperty="(UIElement.Render
Transform).(TransformGroup.Children)[3].(TranslateTransform.Y)">

Clear enough, but what does the TargetProperty value mean? Here is that value highlight below.

(UIElement.RenderTransform).(TransformGroup.Children)[3].

(TranslateTransform.Y)

We know that the net effect of the animation is that the logo moves from above the visible area back to its original position. If we're familiar with X, Y coordinates, where X represents a horizontal coordinate and Y a vertical coordinate, then the TranslateTransform.Y part makes sense. We are changing or, in Silverlight terms, transforming the Y property of the canvas. But what's all this TransformGroup about?

Take a look at our canvas1 node further down in the XAML. You should see the following lines of XAML that weren't there earlier:

<Canvas.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Canvas.RenderTransform>

Blend automatically inserted them into the Canvas when we created the animation. They have no properties. Think of them as stubbed declarations of these objects. If you remove them, Silverlight will throw an exception at runtime like the one below complaining about not being able to resolve TargetProperty:

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Clearly this code is important, but what's really going on here? The TranslateTransform object is a type of Transform object which determines how an object can change in Silverlight. They are packaged in a TransformGroup, which can be set in the RenderTransform property on any object descending from UIElement, which is the base class for any kind of visual element.

With that bit of knowledge, we now see that (TransformGroup.Children)[3] refers to the fourth element in a zero-based collection. Not so coincidentally, the TranslateTransform node is the fourth item inside the TransformGroup in our XAML. Changing the order of the transforms in the XAML will also cause an exception at runtime.

That line of XAML just tells the Silverlight runtime that we're going to animation, now we tell it how and when with our two EasingDoubleKeyFrame nodes:

<EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/>
<EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/>

The first EasingDoubleKeyFrame node tells Silverlight that, at zero seconds, we want the value to be -229. This corresponds to when the logo was above the visible area. The second EasingDoubleKeyFrame node tells Silverlight that at 0.7 seconds, we want the value of the property to be 0. This corresponds to the initial state of the logo, where it was before any transformations were applied.

Silverlight handles all changes to the value in between the start and the end point. Silverlight's default frame rate is 60 frames per second, but Silverlight will adjust its frame rate based on the hardware that it is running on. Silverlight can adjust the amount by which it changes the values to keep the animation on schedule. If you had to reload the web page to see the animation run, then you've already experienced this. Once again, notice how few lines (technically only one line) of procedural code you had to write.

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook
Published: April 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

Have a go hero – exploring animation options

The animation we just created worked, but it feels too mechanical. What if there was a way, we could change the rate at which it "fell down" onto the screen.

In the real world, objects typically bounce when they hit a hard surface. Let's replicate that here by using a built in Easing function. To do this, we will need to do the following:

  1. Go back to Expression Blend and click on the drop down button highlighted here:
  2. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  3. Click on introAnimationStoryboard to edit that timeline.
  4. Click on the key frame oval at 0.7 seconds.
  5. You'll notice that the Properties tab on the right has a combo box that has an angled straight line next to the word None like this:
  6. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  7. Click on the items marked Bounce in the Out Column and the text in the combo box should read Bounce Out like this:
  8. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  9. Run the solution via the menu bar or pressing F5, and notice how the logo bounces onto the screen.
  10. You can also tweak the parameters of the bounce effect by changing the Bounces and Bounciness values.
  11. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  12. To further experiment, you could click on KeySpline where the graph appears, representing the rate of animation. By default, it starts out as a straight line:
  13. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  14. Hit the play button to preview the animation.
  15. You can change the line by clicking and dragging the yellow circles around or by inserting values into the x1,x2, y1,y2 text boxes, so that your graph looks something like this:
  16. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  17. Preview the animation again and note the changes.
  18. Click on the Hold In button highlighted here:

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

Preview the animation once more to see how it just simply "jumps" from one value to the other. Feel free to experiment with different options for animating this logo.

Getting on the same page

So far, we've created two different Silverlight projects; one for the navigation buttons and one for the animated logo. Each resided in their own projects, on their own page. How can we integrate the two projects onto the HTML that we already have for our client's home page?

To do that we should take a look at the test page Blend and Visual Studio automatically created for us and see how to embed a Silverlight application onto a web page.

Time for action – getting Silverlight onto a web page

We need to get both the logo and the navigation buttons on the same page. In this exercise, we're going to bring some new life to our old page:

  1. Open up the CakeNavigationButtons solution in Visual Studio.
  2. Let's take a closer look at the CakeNavigationButtons.Web project.
  3. The project looks much like any other ASP.NET project, except for the ClientBin directory.
  4. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  5. Double-click on the CakeNavigationButtonsTestPage.html to open it in our editor and scroll down the page until you see the following code:
  6. <div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2,"
    type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="ClientBin/CakeNavigationButtons.
    xap"/>
    <param name="onerror" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.41108.0" />
    <param name="autoUpgrade" value="true" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=141205"
    style="text-decoration: none;">
    <img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://go.microsoft.com/fwlink/?LinkId=108181"
    alt="Get Microsoft Silverlight" style="border-style: none"/>
    </a>
    </object>
    <iframe style='visibility:hidden;height:0;width:0;border:0px'>
    </iframe>
    </div>

    Seasoned web developers will instantly recognize a plugin object wrapped inside a DIV tag. The object tag contains a number of param tags, which pass along parameters to the object. By default, the height and width are set to 100%, which fills up all the space available. Combined with the CSS rule #silverlightControlHost, both are Silverlight applications and will be much larger than they need to be. The source parameter points to the CakeNavigationButtons.xap file in the ClientBin directory. The XAP file contains the compiled content of our Silverlight control.

    The minRuntimeVersion parameter indicates that the user must have at least Silverlight 4 in order to run the embedded Silverlight content.

    The HTML inside the object tag is what displays if the user does not have Silverlight installed on their computer. Further up on the page, you'll see a reference to a Silverlight.js file. This contains all the plugin detection code.

  7. Let's go back to our original HTML document, to see where the new code would best fit:
  8. <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Cake-O-Rama</title>
    <style type="text/css">
    <!--
    .Headline {
    color: #039;
    }
    -->
    </style>
    </head>
    <body>
    <h1 align="center" class="Headline">Cake-O-Rama</h1>
    <p align="left"><a href="#">Home</a></p>
    <p align="left"><a href="#">Gallery</a></p>
    <p align="left"><a href="#">Order</a></p>
    <p align="left"><a href="#">Locations</a></p>
    <p align="left"><a href="#">Contact Us</a></p>
    <p align="left"><a href="#">Franchise Opportunities</a></p>
    </body>
    </html>

  9. In the same folder as the Cake-O-Rama HTML file, we will need to create a directory called ClientBin. We could name this directory anything we wanted, but for now, let's stick to the naming convention.
  10. Copy the CakeNavigationButtons.xap and CakeORama_Logo.xap files to the ClientBin directory we just created.
  11. Change the HTML, so that the contents of the body tag are now:
  12. <div align="center">
    <object data="data:application/x-silverlight-2,"
    type="application/x-silverlight-2" width="908" height="258">
    <param name="source" value="ClientBin/CakeORama_Logo.xap"/>
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.41108.0" />
    <param name="autoUpgrade" value="true" />
    <H1 align="center" class="Headline">Cake-O-Rama</H1>
    <a href="http://go.microsoft.com/fwlink/?LinkID=141205"
    style="text-decoration: none;">Get Silverlight</a> to
    experience this site's interactive features.
    </object>
    </div>
    <object data="data:application/x-silverlight-2,"
    type="application/x-silverlight-2" width="214" height="281">
    <param name="source" value="ClientBin/CakeNavigationButtons.xap"/>
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.41108.0" />
    <param name="autoUpgrade" value="true" />
    <p align="left"><a href="#">Home</a></p>
    <p align="left"><a href="#">Gallery</a></p>
    <p align="left"><a href="#">Order</a></p>
    <p align="left"><a href="#">Locations</a></p>
    <p align="left"><a href="#">Contact Us</a></p>
    <p align="left"><a href="#">Franchise Opportunities</a></p>
    <a href="http://go.microsoft.com/fwlink/?LinkID=141205"
    style="text-decoration: none;">Get Silverlight</a> to
    experience this site's interactive features.
    </object>

    Load up the page in your browser. If you're running locally on your file system, you may get an error like this:

    Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

    Or, if you are a user who hasn't installed Silverlight, you may see the following when you load the page:

    Microsoft Silverlight 4 Business Application Development: Beginner’s Guide
  13. Right-click on the security warning bar on the top of the browser window and choose Allow Blocked Content.
  14. Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

  15. The page will reload and you will now see the client's home page in all its Silverlight glory.

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

What just happened?

We took the output of our two Silverlight projects and combined them onto one page. In the process, we saw how Silverlight is embedded onto a static web page.

The client's home page right now is just static HTML, but it can get quite dynamic once you add Silverlight to it. The important thing to remember is that Silverlight is a client-side technology and the backend server could run on any platform.

Summary

In this article, we learned about Animation.

Specifically, we looked at:

  • Creating animations in Silverlight and making them natural by using Easing Key frames
  • Embedding Silverlight controls onto a static web page

If you have read this article you may be interested to view :

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide Build enterprise-ready business applications with Microsoft Silverlight 4 with this book and eBook
Published: April 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

About the Author :


Frank LaVigne

Frank LaVigne has been hooked on software development since he was 12, when he got his own Commodore 64 computer. Since then, he's worked as developer for fi nancial fi rms on Wall Street and also in Europe. He has worked on various Tablet PC soluti ons and on building advanced user experiences in Silverlight and WPF. He lives in the suburbs of Washington, DC. He founded the CapArea.NET User Group Silverlight Special Interest Group and has been recognized by Microsoft as a Tablet PC MVP. He blogs regularly at www.FranksWorld.com.

 

Books From Packt


Microsoft Silverlight 4 Data and Services Cookbook
Microsoft Silverlight 4 Data and Services Cookbook

Pentaho 3.2 Data Integration: Beginner's Guide
Pentaho 3.2 Data Integration: Beginner's Guide

Least Privilege Security for Windows 7, Vista, and XP
Least Privilege Security for Windows 7, Vista, and XP

SketchUp 7.1 for Architectural Visualization: Beginner's Guide
SketchUp 7.1 for Architectural Visualization: Beginner's Guide

Firebug 1.5: Editing, Debugging, and Monitoring Web Pages
Firebug 1.5: Editing, Debugging, and Monitoring Web Pages

Magento 1.3: PHP Developer's Guide
Magento 1.3: PHP Developer's Guide

3D Game Development with Microsoft Silverlight 3: Beginner's Guide
3D Game Development with Microsoft Silverlight 3: Beginner's Guide

CMS Made Simple 1.6: Beginner's Guide
CMS Made Simple 1.6: Beginner's Guide


Your rating: None Average: 5 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
L
f
a
R
v
8
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software