WPF实现路径动画

让目标沿着一条给定的路径移动,使用DoubleAnimationUsingPath类实现。实现如下。

WPF实现路径动画

点击鼠标移动

WPF实现路径动画

实现代码如下:界面XAML

 <Grid x:Name="LayoutRoot">
        <Grid.Resources>
            <PathGeometry x:Key="movingPath" Figures="M 0,150 C300,-100 300,400 600,120"/>
        </Grid.Resources>
        <Button Content="Move" HorizontalAlignment="Left" Height="80" VerticalAlignment="Top" Width="80" Click="Button_Click">
            <Button.RenderTransform>
                <TranslateTransform x:Name="tt" X="0" Y="0"/>
            </Button.RenderTransform>
        </Button>
    </Grid>

CS代码

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            //从XAML代码中获取移动路径数据
            PathGeometry pg = this.LayoutRoot.FindResource("movingPath") as PathGeometry;
            Duration duration = new Duration(TimeSpan .FromMilliseconds(600));

            //创建动画
            DoubleAnimationUsingPath dapX = new DoubleAnimationUsingPath();
            dapX.PathGeometry = pg;
            dapX.Source = PathAnimationSource.X;
            dapX.Duration = duration;

            DoubleAnimationUsingPath dapY = new DoubleAnimationUsingPath();
            dapY.PathGeometry = pg;
            dapY.Source = PathAnimationSource.Y;
            dapY.Duration = duration;

            //执行动画
            this.tt.BeginAnimation(TranslateTransform.XProperty, dapX);
            this.tt.BeginAnimation(TranslateTransform.XProperty, dapY);

            //自动返回、永远循序
            dapX.AutoReverse = true;
            dapX.RepeatBehavior = RepeatBehavior.Forever;
            dapY.AutoReverse = true;
            dapY.RepeatBehavior = RepeatBehavior.Forever;

        }