Pixel-in-Gene

Exploring Creativity with Design / Graphics / Technology

Animating Graphs in WPF Using Clipping Masks

Over the past couple of weeks I have been working on an application that displays a variety of graphs. One of the standard features we have is the load animation for a graph when the user sees it for the first time. For a line graph, this would mean that the graph animates from the left to right and draws itself out.

image

The technique I am using to do this animation is with Clipping Masks. The graph starts out with a Rectangular mask with zero-width and ends with the full-width of the graph after the animation completes. The height of the mask is the same as that of the graph. The following figure shows how my mask grows in size.

image

In Xaml, this can look like so:

1
2
3
4
5
6
<Grid x:Name="GraphContainer">
    <!—Line Graph -->
    <Grid.Clip>
        <RectangleGeometry />
    </Grid.Clip>
</Grid>

The above snippet shows the container on which the Clip mask has been applied. The line graph is inside the GraphContainer. The Storyboard looks like:

1
2
3
4
5
<Storyboard x:Key="GraphClipAnimator">
    <RectAnimation Duration="0:0:1"
                   Storyboard.TargetProperty="Clip.(RectangleGeometry.Rect)"
                   Storyboard.TargetName="GraphContainer"/>
</Storyboard>

Note the use of RectAnimation for expanding the size of the mask. It starts out with a Rect(0, 0, 0, GraphContainer.ActualHeight) and ends with a Rect(0, 0, GraphContainer.ActualWidth, GraphContainer.ActualHeight). We set the From/To values of the RectAnimation inside the Loaded event for the containing Window/UserControl.

The advantage of this technique is that you can choose a more elaborate clipping mask (think of arbitrary PathGeometry) to achieve more fluid graph animations. Also we are not affecting the actual graph in any way and all of the animations are happening on its container. This makes it easy to reuse the technique on multiple graphs.

Comments