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:

<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:

<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.

Similar Posts:

3 responses to “Animating graphs in WPF using Clipping masks”

  1. Trey

    Hi Pavan,

    I see you have done some work with creating graphs. I’m currently building a gantt chart with WPF. Do you have any good design tips?

    The route I’m probably going to take is using an ItemsControl and bind to an ObservableCollection, then modify the ItemTemplate to display a custom bar overlapping a chart.

    Thank you!
    Trey

  2. Jen

    Hi Pavan,

    Please give me some pointer to the approach to implement scrolling/paging and zooming when working on line chart?

    Thanks,
    Jen

Leave a Reply