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.
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.
In Xaml, this can look like so:
1 <Grid x:Name="GraphContainer"> 2 <!—Line Graph --> 3 <Grid.Clip> 4 <RectangleGeometry /> 5 </Grid.Clip> 6 </Grid>
1 <Storyboard x:Key="GraphClipAnimator"> 2 <RectAnimation Duration="0:0:1" 3 Storyboard.TargetProperty="Clip.(RectangleGeometry.Rect)" 4 Storyboard.TargetName="GraphContainer"/> 5 </Storyboard>
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.