Sunday, July 29, 2007

Silverlight 1.0 - How to show a line being drawn

Recently in the official Silverlight forum, several individuals have asked how to dynamically show a line being drawn. This post contains code that will animate a line to look just like the following:



The Silverlight model makes this type of animation very simple. Everything is handled within the XAML code. The XAML code looks like the following:


<Canvas xmlns="http://schemas.microsoft.com/client/2007"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="200">
<Canvas.Triggers>
<EventTrigger RoutedEvent="Canvas.Loaded">
<BeginStoryboard>
<Storyboard Name="lineStoryboard">
<DoubleAnimation Storyboard.TargetName="mainLine" Storyboard.TargetProperty="X2" From="1" To="290" Duration="0:0:8" AutoReverse="false" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Canvas.Triggers>

<Line Name="mainLine" Canvas.Left="5" Canvas.Top="5" X1="0" Y1="0" X2="1" Y2="0" StrokeThickness="2" Stroke="#C0504D"></Line>

<Canvas Name="playAgainCanvas" MouseLeftButtonUp="playAgainCanvas_MouseLeftButtonUp" Canvas.Top="10" Canvas.Left="102">
<Rectangle RadiusX="5" RadiusY="5" Width="95" Height="40" Fill="#9BBB59"></Rectangle>
<TextBlock Text="Play Again" FontFamily="Verdana" Canvas.Left="5" Canvas.Top="10" FontSize="14" FontWeight="Bold" Foreground="white" />
</Canvas>
</Canvas>


The steps, which are derived from the Silverlight SDK, are as follows:

  1. Create a DoubleAnimation. In our case, we are concerned about animating the line being drawn, so the following are key attributes are set:
    • StoryBoard.TargetProperty - Set to X2 because we want to make the line grow in length.
    • From - Set this value to the default X2 position.
    • To - Set this value to the end result (290)
    • Duration - Set this value to 8 seconds just to make it easy to see the line grow.

  2. Place the DoubleAnimation inside of a Storyboard. We give the Storyboard a Name so that we can access it from the client-side code-behind file. This allows us to restart the animation through an event handler associated with the "Play Again" button.

  3. Begin the Storyboard when the Canvas is loaded. This is accomplished through the use of a Trigger



Animation will be covered in Chapter 4 of my upcoming book "Silverlight 1.1 in Action".

I want to apologize to anyone who has been trying to access code samples over the past couple of weeks. I use StreamLoad to host my code samples and they have had some problems over the past couple of weeks. Everything seems to be working better now. If the problems persist, I will look into an alternative solution.

Project Information
    Source Code: here
    Requirements: Silverlight 1.0

No comments: