小编典典

如何在C#中为画布上的线设置动画?

c#

您如何在屏幕上慢慢画一条线?

我正在尝试为C#/ WPF项目中的画布上的线条设置动画。

我想使用C#代码而不是XAML。


阅读 298

收藏
2020-05-19

共1个答案

小编典典

您将需要使用Storyboard和为Line.X2Line.Y2属性设置动画。看看这是否适合您。

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>

按钮单击事件

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);
}
2020-05-19