Search Chirayu Software Solutions Blog

Monday, August 27, 2012

Double Animation in WPF

WPF achieves animation by animating element properties. For example, if you want to produce a zoom in or zoom out effect for a rectangle, you can animate the width and height properties. The following code animates a rectangle by modifying its width and height properties.


<Window x:Class="WpfApplication1.doubleanimation"
        Title="doubleanimation" Height="300" Width="300">
        <Rectangle Name="myrect" Width="1" Height="1">
                <SolidColorBrush Color="Red"/>
                <EventTrigger RoutedEvent="Window.Loaded">
                        <Storyboard RepeatBehavior="Forever">
                            <DoubleAnimation Storyboard.TargetName="myrect"
                       Storyboard.TargetProperty="Width" From="1" To="350"
                       Duration="0:0:1" BeginTime="0:0:0"/>
                            <DoubleAnimation Storyboard.TargetName="myrect"
                       Storyboard.TargetProperty="Height" From="1" To="250"
                       Duration="0:0:1" BeginTime="0:0:1"/>
                            <DoubleAnimation Storyboard.TargetName="myrect"
                       Storyboard.TargetProperty="Height" From="250"
                       To="1" Duration="0:0:1" BeginTime="0:0:2"/>
                            <DoubleAnimation Storyboard.TargetName="myrect"
                       Storyboard.TargetProperty="Width" From="350" To="1"
                       Duration="0:0:1" BeginTime="0:0:3"/>

Following is the output of the above code:


This code triggers the animation automatically when the window is loaded. The code adds an EventTrigger to the rectangle. The BeginStoryboard action runs a storyboard. This storyboard uses fourDoubleAnimations. The first DoubleAnimation increases the width of the rectangle from 1 to 350. The second one increases the height from 1 to 250. The third and fourth do the reverse by decreasing the height and width back to 1. The four DoubleAnimations are made to run in a sequence by setting the BeginTimeattribute such that each animation starts when the previous is over. The RepeatBehavior attribute of the Storyboard is assigned the value "Forever" which makes the animation run indefinitely. 

No comments: