如果我理解您的意思正确,您想要将线条动画显示为刚刚被绘制出来的样子。以下是一个使用您提供的数值的简单示例。
<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="lineCanvas" MouseLeftButtonDown="lineCanvas_MouseLeftButtonDown" Background="White" />
</Window>
事件处理程序稍后将启动动画。首先,我们将定义数据:
List<Point> Points = new List<Point>();
Storyboard sb;
public MainWindow()
{
InitializeComponent();
Points.Add(new Point(10, 20));
Points.Add(new Point(50, 30));
Points.Add(new Point(20, 20));
Points.Add(new Point(40, 22));
Points.Add(new Point(45, 20));
Points.Add(new Point(50, 35));
InitAnimation();
}
sb
是包含动画的 Storyboard
。可以轻松地从文件中填充 Points
的值。
让我们初始化动画。每个线段都会添加一行新的内容。然后,线段的终点将被动画化。
public void InitAnimation()
{
sb = new Storyboard();
for (int i = 0; i < Points.Count - 1; ++i)
{
var l = new Line();
l.Stroke = Brushes.Black;
l.StrokeThickness = 2;
var startPoint = Points[i];
var endPoint = Points[i + 1];
l.X1 = startPoint.X;
l.Y1 = startPoint.Y;
l.X2 = startPoint.X;
l.Y2 = startPoint.Y;
lineCanvas.Children.Add(l);
var daX = new DoubleAnimation(endPoint.X, new Duration(TimeSpan.FromMilliseconds(1000)));
var daY = new DoubleAnimation(endPoint.Y, new Duration(TimeSpan.FromMilliseconds(1000)));
daX.BeginTime = TimeSpan.FromMilliseconds(i * 1010);
daY.BeginTime = TimeSpan.FromMilliseconds(i * 1010);
sb.Children.Add(daX);
sb.Children.Add(daY);
Storyboard.SetTarget(daX, l);
Storyboard.SetTarget(daY, l);
Storyboard.SetTargetProperty(daX, new PropertyPath(Line.X2Property));
Storyboard.SetTargetProperty(daY, new PropertyPath(Line.Y2Property));
}
}
动画的持续时间可以根据线条的长度轻松更改,使其看起来更加美观。
最后一个任务,展示动画:
private void lineCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
sb.Begin(this);
}