如何在 C# 中为画布上的线条设置动画?
问题描述:
你会如何让一条线慢慢地划过屏幕?
How would you make a line slowly draw across the screen?
我正在尝试为 C#/WPF 项目的画布上的线条设置动画.
I am trying to animate a line on a canvas in a C#/WPF project.
我想使用 C# 代码而不是 XAML.
I would like to use C# code and not XAML.
答
您将需要使用 Storyboard
并为 Line.X2
和 Line 设置动画.Y2
属性.看看这是否适合你.
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>
按钮点击事件
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);
}