How do you animate a line on a canvas in C#?

animation, c#, canvas, wpf

Solution

You will need to use a `Storyboard` and animate the `Line.X2` and `Line.Y2` Properties. See if this works for you.

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas Name="myCanvas">
        <Button Canvas.Left="248" Canvas.Top="222" Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
    </Canvas>
</Window>

Button Click Event

private void button1_Click(object sender, RoutedEventArgs e)
{
    Line line = new Line();
    myCanvas.Children.Add(line);
    line.Stroke = Brushes.Red;
    line.StrokeThickness = 2;
    line.X1 = 0;
    line.Y1 = 0;

    Storyboard sb = new Storyboard();
    DoubleAnimation da = new DoubleAnimation(line.Y2 , 100, new Duration(new TimeSpan(0, 0, 1)));
    DoubleAnimation da1 = new DoubleAnimation(line.X2, 100, new Duration(new TimeSpan(0, 0, 1)));
    Storyboard.SetTargetProperty(da, new PropertyPath("(Line.Y2)"));
    Storyboard.SetTargetProperty(da1, new PropertyPath("(Line.X2)"));
    sb.Children.Add(da);
    sb.Children.Add(da1);

    line.BeginStoryboard(sb);
}

Problem

How would you make a line slowly draw across the screen? I am trying to animate a line on a canvas in a C#/WPF project. I would like to use C# code and not XAML.

Original source