Animations


With animations you can make a smooth transition using moving elements, color changes, transforms, and so on. WPF makes it easy to create animations. You can animate the value of any dependency property. Different animation classes exist to animate the values of different properties, depending on their type.

The major elements of animations:

  • Timeline - The timeline defines how a value changes over time. Different kinds of timelines are available for changing different types of values. The base class for all timelines is Timeline. To animate a double, the class DoubleAnimation can be used. Int32Animation is the animation class for int values.

  • Storyboard - A storyboard is used to combine animations. The Storyboard class itself is derived from the base class TimelineGroup, which derives from Timeline. With DoubleAnimation you can animate a double value; with a Storyboard you combine all the animations that belong together.

  • Triggers - With triggers you can start and stop animations. Previously you’ve seen property triggers. Property triggers fire when a property value changes. You can also create an event trigger. An event trigger fires when an event occurs.

The following example defines the style AnimatedButtonStyle for buttons. In the template a rectangle named outline is defined. This template has a thin stroke with the thickness set to 0.4.

The template has a property trigger for the IsMouseOver property defined. The EnterActions property of this trigger applies as soon as the mouse is moved over the button. The action to start is BeginStoryboard. BeginStoryboard is a trigger action that can contain and thus start Storyboard elements. The Storyboard element defines a DoubleAnimation to animate a double value. The property value that is changed in this animation is the Rectangle.StrokeThickness of the Rectangle element with the name outline. The value is changed in a smooth way by 1.2, as the By property specifies, for a time length of 0.3 seconds as specified by the Duration property. At the end of the animation, the stroke thickness is reset to its original value because AutoReverse=”True”. To summarize: as soon as the mouse moves over the button, the thickness of the outline is incremented by 1.2 for 0.3 seconds. Figure 31-32 shows the button without animation, and Figure 31-33 shows the button at the moment 0.3 seconds after the mouse moved over it. It’s just not possible to show the smooth animation and intermediate looks in a print medium.

 <Window x:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     Title="Animation Sample" Height="300" Width="300">   <Window.Resources>     <Style x:Key="AnimatedButtonStyle" TargetType="{x:Type Button}">       <Setter Property="Template">         <Setter.Value>           <ControlTemplate TargetType="{x:Type Button}">             <Grid>                <Rectangle Name="outline" RadiusX="9" RadiusY="9" Stroke="Black"                           Fill="{TemplateBinding Background}" StrokeThickness="0.4">                </Rectangle>                <ContentPresenter VerticalAlignment="Center"                      HorizontalAlignment="Center"                       />              </Grid>              <ControlTemplate.Triggers>                <Trigger Property="IsMouseOver" Value="True">                  <Trigger.EnterActions>                    <BeginStoryboard>                      <Storyboard>                       <DoubleAnimation Duration="0:0:0.3" AutoReverse="True"                              Storyboard.TargetProperty="(Rectangle.StrokeThickness)"                              Storyboard.TargetName="outline" By="1.2" />                      </Storyboard>                    </BeginStoryboard>                  </Trigger.EnterActions>                </Trigger>              </ControlTemplate.Triggers>            </ControlTemplate>          </Setter.Value>        </Setter>      </Style>    </Window.Resources>    <Grid>      <Button Style="{StaticResource MyButtonStyle}" Width="200" Height="100">            Click Me!      </Button>    </Grid> </Window>

image from book
Figure 31-32

image from book
Figure 31-33

Things you can do with a Timeline are listed in the following table.

Open table as spreadsheet

Timeline Properties

Description

AutoReverse

With the AutoReverse property, you can specify if the value that is animated should return to the original value after the animation.

SpeedRatio

With the SpeedRatio, you can transform the speed at which an animation moves. With this property, you can define the relation in regard to the parent. The default value is 1; setting the ratio to a smaller value, makes the animation moves slower; setting the value to a higher value than 1 makes it move faster.

BeginTime

With BeginTime you can specify the timespan from the start of the trigger event until the moment the animation should start. You can specify days, hours, minutes, seconds, and fractions of seconds. This might not be the real time, depending on the speed ratio. For example, if the speed ratio is set to 2, and the beginning time is set to 6 seconds, the animation will start after 3 seconds.

AccelerationRatio

DecelerationRatio

With an animation the values need not be changed in a linear way. You can specify an AccelerationRatio and DecelerationRatio to define the impact of acceleration and deceleration. The sum of both values set must not be greater than 1.

Duration

With the Duration property, you specify the time length for one iteration of the animation.

RepeatBehavior

Assigning a RepeatBehavior struct to the RepeatBehavior property lets you can define how many times or how long the animation should be repeated.

FillBehavior

The FillBehavior property is important if the parent timeline has a different duration. For example, if the parent timeline is shorter than the duration of the actual animation, setting the FillBehavior to Stop means that the actual animation stops. If the parent timeline is longer than the duration of the actual animation, HoldEnd keeps the actual animation active before resett ing it to its original value (if AutoReverse is set).

Depending on the type of the Timeline class, some more properties may be available. For example, with DoubleAnimation you can specify the following additional properties.

Open table as spreadsheet

DoubleAnimation Properties

Description

From

To

By setting the From and To properties, you can specify the values to start and end the animation.

By

Instead of defining the start value for the animation, by setting the By property the animation starts with the current value of the bound property and is incremented with the value specified by the By property for the animation’s end.

Instead of having a property trigger, you can define an event trigger to start the animation. The next example creates an animation for the funny face you know from the earlier example where the eye moves as soon a Click event from a button is fired. This example also demonstrates that you can start the animation both from XAML and code behind.

Figure 31-34 shows the design view of the animated face example.

image from book
Figure 31-34

Inside the Window element a DockPanel element is defined to arrange the funny face and the buttons. A Grid containing the Canvas element is docked on top. Bottom-docking is configured with a StackPanel element that contains four buttons. The first two buttons are used to animate the eye from code behind; the last two buttons are used to animate the eye from XAML.

The animation is defined within the <DockPanel.Triggers> section. Instead of a property trigger, an event trigger is used. The first event trigger is fired as soon as the Click event occurs with the button startButtonXAML defined by the RoutedEvent and SourceName properties. The trigger action is defined by the BeginStoryboard element that starts the containing Storyboard. BeginStoryboard has a name defined, as this is needed to control the storyboard with pause, continue, and stop actions. The Storyboard element contains two animations. The first animation changes the Canvas.Left position value of the eye; the second animation changes the Canvas.Top value. Both animations have different time values that make the eye movement very interesting using the defined repeated behavior.

The second event trigger is fired as soon as the Click event of the stopButtonXAML button occurs. Here, the storyboard is stopped with the StopStoryboard element, which references the started storyboard beginMoveEye.

 <Window x:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     Title="Animated Face" Height="300" Width="406">   <DockPanel>     <Grid DockPanel.Dock="Top">       <!-- Funny Face -->       <Canvas Width="200" Height="200">         <Ellipse Canvas.Left="50" Canvas.Top="50" Width="100" Height="100"             Stroke="Blue" StrokeThickness="4" Fill="Yellow" />          <Ellipse Canvas.Left="60" Canvas.Top="65" Width="25" Height="25"              Stroke="Blue" StrokeThickness="3" Fill="White" />          <Ellipse Name="eye" Canvas.Left="67" Canvas.Top="72" Width="5"              Height="5" Fill="Black" />          <Path Name="mouth" Stroke="Blue" StrokeThickness="4"              Data="M 62,125 Q 95,122 102,108" />          <Line Name="LeftLeg" X1="92" X2="82" Y1="146" Y2="168" Stroke="Blue"              StrokeThickness="4" />          <Line Name="LeftFoot" X1="68" X2="83" Y1="160" Y2="169" Stroke="Blue"              StrokeThickness="4" />          <Line Name="RightLeg" X1="124" X2="132" Y1="144" Y2="166" Stroke="Blue"              StrokeThickness="4" />          <Line Name="RightFoot" X1="114" X2="133" Y1="169" Y2="166" Stroke="Blue"              StrokeThickness="4" />        </Canvas>      </Grid>      <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">        <Button Width="80" Height="40" Margin="20,5,5,5"           Name="startAnimationButton">Start</Button>        <Button Width="80" Height="40" Margin="5,5,5,5"           Name="stopAnimationButton">Stop</Button>        <Button Width="80" Height="40" Margin="5,5,5,5"           Name="startButtonXAML">Start</Button>        <Button Width="80" Height="40" Margin="5,5,5,5"           Name="stopButtonXAML">Stop       </Button>     </StackPanel>     <DockPanel.Triggers>       <EventTrigger RoutedEvent="Button.Click" SourceName="startButtonXAML">         <BeginStoryboard Name="beginMoveEye">           <Storyboard Name="moveEye">             <DoubleAnimation RepeatBehavior="Forever" DecelerationRatio=".8"                 AutoReverse="True" By="8" Duration="0:0:1"                 Storyboard.TargetName="eye"                 Storyboard.TargetProperty="(Canvas.Left)" />             <DoubleAnimation RepeatBehavior="Forever" AutoReverse="True" By="8"                 Duration="0:0:5" Storyboard.TargetName="eye"                 Storyboard.TargetProperty="(Canvas.Top)" />           </Storyboard>         </BeginStoryboard>       </EventTrigger>              <EventTrigger RoutedEvent="Button.Click" SourceName="stopButtonXAML">         <StopStoryboard BeginStoryboardName="beginMoveEye" />       </EventTrigger>     </DockPanel.Triggers>   </DockPanel> </Window>

Instead of starting and stopping the animation directly from event triggers in XAML, you can easily control the animation from code behind. The buttons startAnimationButton and stopAnimationButton have the event handlers OnStartAnimation and OnStopAnimation associated with them. Within the event handlers, the animation is started with the Begin() method and stopped with the Stop() method. With the Begin() method the second parameter is set to true to allow you to control the animation with a stop request.

 public partial class Window1 : System.Windows.Window {    public Window1()    {       InitializeComponent();       startAnimationButton.Click += OnStartAnimation;       stopAnimationButton.Click += OnStopAnimation;    }     void OnStartAnimation(object sender, RoutedEventArgs e)    {       moveEye.Begin(eye, true);    }    void OnStopAnimation(object sender, RoutedEventArgs e)    {       moveEye.Stop(eye);    } }

Now, you can start the application and watch the eye move as soon as one of the Start buttons is clicked.

The Storyboard class inherits from the base class Timeline but can contain multiple time -lines. The Storyboard class can be used to control timelines. The following table describes the methods of the Storyboard class.

Open table as spreadsheet

Storyboard Methods

Description

Begin()

The Begin() method starts the animations associated with the storyboard.

BeginAnimation()

With BeginAnimation(), you can start a single animation for a dependency property.

CreateClock()

The CreateClock() method returns a Clock object that you can use to the control the animations.

Pause()

Resume()

With Pause() and Resume(), you can pause and resume animations.

Seek()

With the Seek() method, you can jump in time and move the animation to a specified time interval.

Stop()

The Stop() method halts the clock and stops the animation.

The EventTrigger class makes it possible to define actions when events occur. The following table describes the properties of this class.

Open table as spreadsheet

EventTrigger Properties

Description

RoutedEvent

With the RoutedEvent property, you can define the event when the trigger should start, for example, a Click event of a Button.

SourceName

The SourceName property defines to what WPF element the event should connect.

Trigger actions that you can put within an EventTrigger are listed in the following table. In the example you’ve seen the BeginStoryboard and StopStoryboard actions, but the following table shows some others.

Open table as spreadsheet

TriggerAction Class

Decription

SoundPlayerAction

With the SoundPlayerAction, you can play a .wav file.

BeginStoryboard

BeginStoryboard starts an animation defined by a Storyboard.

PauseStoryboard

PauseStoryboard pauses an animation.

ResumeStoryboard

ResumeStoryboard resumes an animation that was paused.

StopStoryboard

StopStoryboard stops a running animation.

SeekStoryboard

With Seekstoryboard, you can change the current time of an animation.

SkipStoryboardToFill

SkipStoryboardToFill advances an animation to the fill period at the end.

SetStoryboardSpeedRatio

With SetStoryboardSpeedRatio, you can change the speed of an animation.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net