在 WPF 中,您可以简单地为 Line 控件设置动画。
<Canvas>
<Line x:Name="line"
X2="{Binding X1, RelativeSource={RelativeSource Mode=Self}}"
Y2="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Stroke="Red" StrokeThickness="4">
</Line>
</Canvas>
您将使用如下方法创建并启动动画:
private void StartAnimation()
{
var animation = new DoubleAnimation
{
To = ActualWidth, // width of the window
Duration = TimeSpan.FromSeconds(ActualWidth / 32),
RepeatBehavior = RepeatBehavior.Forever
};
line.BeginAnimation(Line.X1Property, animation);
}
除了为X1
Line 的属性设置动画并让X2
属性跟随绑定之外,您还可以为 Line 的 RenderTransform 设置动画:
<Canvas>
<Line Y2="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Stroke="Red" StrokeThickness="4">
<Line.RenderTransform>
<TranslateTransform x:Name="transform"/>
</Line.RenderTransform>
</Line>
</Canvas>
StartAnimation 方法现在看起来像这样:
private void StartAnimation()
{
var animation = new DoubleAnimation
{
To = ActualWidth, // width of the window
Duration = TimeSpan.FromSeconds(ActualWidth / 32),
RepeatBehavior = RepeatBehavior.Forever
};
transform.BeginAnimation(TranslateTransform.XProperty, animation);
}