您需要DoubleAnimationUsingPath
(ref):
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
<Storyboard x:Key="Storyboard1">
<DoubleAnimationUsingPath Duration="0:0:2" Source="X" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="object">
<DoubleAnimationUsingPath.PathGeometry>
<PathGeometry Figures="M2,10 L52,-35 L202,-35 L252,10"/>
</DoubleAnimationUsingPath.PathGeometry>
</DoubleAnimationUsingPath>
<DoubleAnimationUsingPath Duration="0:0:2" Source="Y" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="object">
<DoubleAnimationUsingPath.PathGeometry>
<PathGeometry Figures="M2,10 L52,-35 L202,-35 L252,10"/>
</DoubleAnimationUsingPath.PathGeometry>
</DoubleAnimationUsingPath>
</Storyboard>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<Canvas Background="Gray" Margin="10">
<Ellipse x:Name="Node1" Width="20" Height="20" Fill="AliceBlue" Canvas.Left="38" Canvas.Top="136" />
<Ellipse x:Name="Node2" Width="20" Height="20" Fill="AliceBlue" Canvas.Left="290" Canvas.Top="136" />
<Ellipse x:Name="object" Width="10" Height="20" Fill="Black" Canvas.Left="43" Canvas.Top="125" RenderTransformOrigin="0.5,0.5" MouseLeftButtonDown="object_MouseLeftButtonDown" >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
<Path Stroke="Black" StrokeThickness="1">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection>
<PathFigure StartPoint="50,145">
<PathFigure.Segments>
<PathSegmentCollection>
<LineSegment Point="100,100" />
<LineSegment Point="250,100" />
<LineSegment Point="300,145" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathFigureCollection>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
</Grid>
</Window>
然後從代碼中調用:
private void object_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Storyboard animation = this.TryFindResource("Storyboard1") as Storyboard;
animation.Begin();
}
[編輯] 我想你在這裏失去了重要的工具:Blend。至於在代碼中創建動畫,如果你看看XAML元素,想想他們爲序列化的類,它可以在代碼中得到體現,即
Storyboard sb = new Storyboard();
DoubleAnimationUsingPath ani_2 = new DoubleAnimationUsingPath();
ani_2.Duration = new Duration(new TimeSpan(0, 0, 2));
PathGeometry pg = new PathGeometry();
pg.Figures.Add(new PathFigure());
ani_2.PathGeometry.AddGeometry(pg);
等,但它是(IMAO)相當痛苦創建這些直來自代碼。這一切都取決於應用程序。 看一看here作爲Blend的起點。
我測試使用你的方法,它工作正常。但是,我還是不明白這裏的一些事情。您如何創建動畫中使用的路徑幾何圖形?我將如何通過C#代碼創建它們?舉例來說,我需要在用戶繪製的路徑上爲此對象設置動畫,我將如何將路徑轉換爲路徑幾何? – SysAdmin
爲什麼Canvas.GetLeft(@object)在動畫結束後不會改變?如果你能提供一個好的教程的鏈接來理解這些基本的東西,那也是有幫助的。 – SysAdmin
看看更新的文章 – StaWho