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.

CODE:

<Window x:Class="WpfApplication1.doubleanimation"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="doubleanimation" Height="300" Width="300">
    <Grid>
        <Rectangle Name="myrect" Width="1" Height="1">
            <Rectangle.Fill>
                <SolidColorBrush Color="Red"/>
            </Rectangle.Fill>
            <Rectangle.Triggers>
                <EventTrigger RoutedEvent="Window.Loaded">
                    <BeginStoryboard>
                        <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"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Rectangle.Triggers>
        </Rectangle>
    </Grid>
</Window>


Following is the output of the above code:

EXPLANATION:

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. 
Post a Comment