Animating your XAML Apps

 

XAMLAnimation.jpg

Figure 1 - Animation in XAML

 

Introduction

XAML is not only useful for describing the controls on your forms.  XAML provides a means for drawing graphics in your window.  The graphics can be stationary or animated and they can all be described in XML.  In this article we will take a look at some of the capability of drawing to the XAML canvas using XML.

Drawing in XAML

Let's start by putting a simple polygon inside our window.  The polygon has properties name(name of polygon variable), stroke (outline color), StrokeThickness (like pen thickness of outline), Points (actual points describing the shape),  Polygon.Fill  (what brush  to fill the polygon with)

Listing 1 - Polygon described in XAML

<Window x:Class="XAMLAnimation.Window1"
   
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   
Title="XAML Animation - Spinning Stars" Height="300" Width="355">

    <Grid Name="myGrid">
      <
Canvas Margin="15,18,18,26" MinHeight="50" MinWidth="50" Name="canvas1">
        <!--
Draw a star shape  -->
        <
Polygon
          
Name ="mypolygon1"
           Stroke="Blue"
          
StrokeThickness="1.0"     
          
Points="176.5,50 189.2,155.003 286.485,113.5 201.9,177 286.485,240.5
                      189.2,198.997 176.5,304 163.8,198.997 66.5148,240.5 151.1,177
                      66.5148,113.5 163.8,155.003
">

           <Polygon.Fill>
              <
SolidColorBrush Color="Blue" />
            </
Polygon.Fill>

          </Polygon>
      </
Canvas>
  </
Grid>
</
Window>

.NET 3.0 gives you the flexibility of either describing the polygon in XAML or in C#.  Here is the equivalent polygon in code.

Listing 2 - Polygon drawn using C#

myPolygon1 = new Polygon();
myPolygon.Stroke = Brushes.Blue;
myPolygon.Fill = Brushes.Blue;
myPolygon.StrokeThickness = 1;
Point Point1 = new Point(
176, 50);
Point Point2 = new Point(190,155);
Point Point3 = new Point(286,113);

...
PointCollection myPointCollection = new PointCollection();
myPointCollection.Add(Point1);
myPointCollection.Add(Point2);
myPointCollection.Add(Point3);
myPolygon.Points = myPointCollection;
myGrid.Children.Add(myPolygon1);

Now that we have drawn our blue star, it would be fun to be able to move, rotate, and size it.  Let's examine transforming our polygon using XAML.

Transforming Shapes in XAML

XAML provides a set of transformation descriptions for all shapes including Translation, Rotation, Scaling, Stretching. Below is a table describing each of them.  (Note there are also similar transformations provided for 3D manipulation: RotateTransform3D, TranslateTransform3D, and ScaleTransform3D ):

Table 1 - 2D Transformations for XAML Shapes

Transformation XAML XAML Example
Rotation RotateTransform

 <RotateTransform x:Name="rotateIt" CenterX="176" CenterY="145" Angle="45" />

Translation TranslateTransform

<TranslateTransform x:Name="translateIt" X ="-50" Y="50" />

Skewing SkewTransform <SkewTransform CenterX="50" CenterY="50" AngleX="30" AngleY="0" />
Scaling ScaleTransform

<ScaleTransform x:Name ="scaleIt" ScaleX=".25" ScaleY=".25" />

If you want to perform several transformations on a shape, you need to wrap it in a TransformationGroup.   Below is the transformations for shrinking, moving, and rotating our polygon star in the canvas.  The RotateTransform tells the polygon to rotate 90 degrees around the point 176, 145 of the polygon.  The TranslateTransform moves the polygon 50 pixes up and 50 pixels to the left.  The ScaleTransform shrinks the polygon to 1/4 of it's current size.

Listing 3 - Rendering the Polygon using 3 Transforms

          <Polygon.RenderTransform>
            <
TransformGroup>
              <
RotateTransform x:Name="xformRotate" CenterX="176" CenterY="145" Angle="90" />
              <
TranslateTransform x:Name="xformTranslate" X ="-50" Y="-50" />
              <
ScaleTransform x:Name ="xformScale" ScaleX=".25" ScaleY=".25" />
            </
TransformGroup>
            </
Polygon.RenderTransform>

Also, in order to also render the polygon using the transforms on the canvas, we inserted the transform group within the RenderTransform tag for the Polygon shape.

Now that we know how to perform all the cool transformations on the polygon let's get it moving inside the Window!

Animation in XAML

XAML uses the concept of a story board to give you a framework in which to animate your shape.  The elements within the storyboard are called Animation objects.  There are 4 types of animations in 2D XAML:  DoubleAnimation, ColorAnimation, VectorAnimation, and PointAnimation. Basically each animation varies a single property within the shape over a specified time frame.  For example, a DoubleAnimation varies a double property over a period of time,  and a ColorAnimation will vary a color property over a period of time.  You just need to specify the property you want to vary and the time frame, and your off and animating!  For motion, you can specify the actual transform of the object you want to animate and then vary the transform property to get the desired animation effect over time.  For color animation, you can specify the brush you are varying.  (Note you need to make sure your XAML transform, or brush within your shape has a name attribute specified, so you can refer to it in the Storyboard.TargetName)

Table 2 - Different Animations in XAML

XAML Description XAML Example
DoubleAnimation varies a double property of the shape over a time period

       <DoubleAnimation Storyboard.TargetName="KennyRotateIt"
                                    
Storyboard.TargetProperty="Angle"
                                    
From="0" To="360" Duration="0:0:01"
                                    
RepeatBehavior="Forever" />

DoubleAnimationUsingKeyFrames allows you to vary a double property over a set of timespans.  the shapes movement will be linearly interpreted from one position to the next.  e.g. it will move to the 10 position in the first 3 seconds.  To the 100 position in the next 2 seconds, and to the 200 position in the final 5 seconds.    <DoubleAnimationUsingKeyFrames
                     
Storyboard.TargetName="KennyTranslateIt"
                        
Storyboard.TargetProperty="X"
                        
Duration="0:0:10">
                      <
LinearDoubleKeyFrame Value="10" KeyTime="0:0:3" />
                      <
LinearDoubleKeyFrame Value="100" KeyTime="0:0:5" />
                      <
LinearDoubleKeyFrame Value="200" KeyTime="0:0:10" />
                    </
DoubleAnimationUsingKeyFrames>
ColorAnimation varies a color property of the shape going from one color to a new color over a period of time

<ColorAnimation Storyboard.TargetName="mybrush" Storyboard.TargetProperty="Color" From="Red" To="Blue" Duration="0:0:7"

 

VectorAnimation Allows you to vary a Vector property of the shape over time  
VectorAnimationUsingKeyFrames Allows you to animate a shape using a vector over a set of timespans

                 

 

PointAnimation Allows you to vary a point property of the shape over time, such as the center of a shape

 <PointAnimation     Storyboard.TargetProperty="Center"                      Storyboard.TargetName="MyAnimatedEllipseGeometry"                      Duration="0:0:2" From="200,100" To="450,250" RepeatBehavior="Forever" />


 

As we mentioned, the storyboard is a collection of animation objects that vary properties.  Listing 4 shows the animation XAML for moving a polygon across the screen.  Here we are only affecting the TranslationTransform, so we are varying the X property of the Translation using a DoubleAnimation.   In the example in listing 4, we vary the offset of X from 1 to 750 pixels over a period of 14 seconds.  Setting AutoReverse to true allows us to send the spinning star back in the opposite direction (from 750 to 1).

Listing 4 - Moving a Star back and forth across the screen

            <Polygon.Triggers>
              <
EventTrigger RoutedEvent="Polygon.Loaded">
                <
EventTrigger.Actions>
                  <
BeginStoryboard>
                  <
Storyboard>
                    <!--
Translate from 1 to 750 pixels, repeated, back-and-forth  -->
                    <
DoubleAnimation Storyboard.TargetName="xformTranslate"
                                    
Storyboard.TargetProperty="X"
                                    
From="1" To="750" Duration="0:0:14"
                                    
AutoReverse ="True" RepeatBehavior="Forever" />

                  </Storyboard>
                  </
BeginStoryboard>
                </
EventTrigger.Actions>
              </
EventTrigger>
            </
Polygon.Triggers>

If we want to have the star spin as it moves across the screen, we need to add a DoubleAnimation for the rotational transform.  Listing 5 gets are polygon star spinning through a 360 degree angle as it moves back and forth across the form.

Listing 5 - Rotating our Star

            <Polygon.Triggers>
              <
EventTrigger RoutedEvent="Polygon.Loaded">
                <
EventTrigger.Actions>
                  <
BeginStoryboard>
                  <
Storyboard>
                    <!--
RotateTransform angle from 0 to 360 in 1 second, repeated forever -->
                    <
DoubleAnimation Storyboard.TargetName="xformRotate"
                                    
Storyboard.TargetProperty="Angle"
                                    
From="0" To="360" Duration="0:0:01"
                                    
RepeatBehavior="Forever" />

                    <
DoubleAnimation Storyboard.TargetName="xformTranslate"
                                    
Storyboard.TargetProperty="X"
                                    
From="1" To="750" Duration="0:0:14"
                                    
AutoReverse ="True" RepeatBehavior="Forever" />

                  </Storyboard>
                  </
BeginStoryboard>
                </
EventTrigger.Actions>
              </
EventTrigger>
              </
Polygon.Triggers>

Finally, we can animate the internal fill color of the star by changing it from blue to red in a smooth transition.  We simply drive the color change through the ColorAnimation tag.  We can control the colors to change and the rate of change by specifying a duration shown in listing 7.  Note that we had to give the brush that we are animating a name as shown in listing 6, so we can refer to it in the color animation shown in listing 7:

Listing 6 - Naming the Fill Brush in Xaml

<Polygon.Fill>
     <
SolidColorBrush x:Name ="mybrush" Color="Red" />
</Polygon.Fill>


Listing 7 - Animating Color in XAML

            <Polygon.Triggers>
              <
EventTrigger RoutedEvent="Polygon.Loaded">
                <
EventTrigger.Actions>
                  <
BeginStoryboard>
                  <
Storyboard>
                    <!--
Animate the color from red to blue, and from blue to red in 7 seconds -->
                     <
ColorAnimation Storyboard.TargetName="mybrush"
                        Storyboard.TargetProperty
="Color"
                        From
="Red" To="Blue" Duration="0:0:7"
                       
RepeatBehavior="Forever" AutoReverse="True"/>

                    <
DoubleAnimation Storyboard.TargetName="xformRotate"
                                    
Storyboard.TargetProperty="Angle"
                                    
From="0" To="360" Duration="0:0:01"
                                    
RepeatBehavior="Forever" />

                    <
DoubleAnimation Storyboard.TargetName="xformTranslate"
                                    
Storyboard.TargetProperty="X"
                                    
From="1" To="750" Duration="0:0:14"
                                    
AutoReverse ="True" RepeatBehavior="Forever" />

                  </Storyboard>
                  </
BeginStoryboard>
                </
EventTrigger.Actions>
              </
EventTrigger>
              </
Polygon.Triggers>

Animating a Bitmap

Animating a polygon was fun, but let's see how to animate a bitmap.  There really is very little difference between animating a shape and animating a bitmap.  The bitmap of Kenny is defined the same way as a polygon would be defined in Xaml.   The only difference is the property attributes used to define the image (such as the Source attribute which defines the bitmap's filename).  The transforms of the image are defined exactly the same way as the transforms of the polygon.

Listing 8 - Describing an image of Kenny in XAML

<Image Margin="75,61,0,119" Name="image1" Source="Images\KENNY.bmp" HorizontalAlignment="Left" Width="72">
          <
Image.RenderTransform>
            <
TransformGroup>
              <
RotateTransform x:Name="KennyRotateIt"   CenterX="50" CenterY="50" Angle="45"  />
              <
ScaleTransform x:Name="KennyScaleIt" ScaleX=".75" ScaleY=".75" />
              <
TranslateTransform  x:Name="KennyTranslateIt" X="0" Y="100" />
            </
TransformGroup>
          </
Image.RenderTransform>

...

The storyboard doesn't change in structure going from a polygon to a bitmap.  In our example in listing 8 we added a twist in the animation by accelerating Kenny across the screen using Key Frames.  The key frames give the affect of jolting Kenny across our form at different time frames. (Maybe we should have animated a lightening bolt behind him, which would have been more appropriate for Kenny's character).

Listing 9 - Jolting Kenny across the screen using Key Frames

<Image.Triggers>
            <
EventTrigger RoutedEvent="Image.Loaded">
              <
EventTrigger.Actions>
                <
BeginStoryboard>
                  <
Storyboard x:Name="myStoryBoard1" Completed="OnCompletedAnimation">
                    <
DoubleAnimation Storyboard.TargetName="KennyRotateIt"
                                    
Storyboard.TargetProperty="Angle"
                                    
From="0" To="360" Duration="0:0:01"
                                    
RepeatBehavior="Forever" />
 

                    <!-- Jolt Kenny across the screen at different time frames -->
                    <
DoubleAnimationUsingKeyFrames
                        
Storyboard.TargetName="KennyTranslateIt"
                        
Storyboard.TargetProperty="X"
                        
Duration="0:0:10" AutoReverse="True" RepeatBehavior="Forever">
                      <!--
These KeyTime properties are specified as TimeSpan values
                 which are in the form of "hours:minutes:seconds".
-->
                      <
LinearDoubleKeyFrame Value="10" KeyTime="0:0:3" />
                      <
LinearDoubleKeyFrame Value="100" KeyTime="0:0:5" />
                      <
LinearDoubleKeyFrame Value="200" KeyTime="0:0:10" />
                    </
DoubleAnimationUsingKeyFrames>
                  </
Storyboard>
                </
BeginStoryboard>
              </
EventTrigger.Actions>
            </
EventTrigger>
 </
Image.Triggers>

Conclusion

XAML  introduces a way to do animation through a simple set of rules which you can insert in a storyboard.  With these rules you can create fun 2D and 3D animation scenes to include in your software. Hopefully in the future we will be able to show you how to leverage this capability for some simple games.  In the meantime don't be afraid to share your animation stories with others so they can leverage the power of XAML and .NET


Recommended Free Ebook
Similar Articles