Partager via


Aperçu des animations de trajectoire

Cette rubrique présente les animations de chemin d’accès, qui vous permettent d’utiliser un chemin géométrique pour générer des valeurs de sortie. Les animations de chemin d’accès sont utiles pour déplacer et faire pivoter des objets le long de chemins complexes.

Conditions préalables

Pour comprendre cette rubrique, vous devez être familiarisé avec les fonctionnalités d’animations WPF. Pour une présentation des fonctionnalités d’animation, consultez la vue d’ensemble de l’animation.

Étant donné que vous utilisez un objet PathGeometry pour définir une animation de chemin d’accès, vous devez également être familiarisé avec PathGeometry et les différents types d’objets PathSegment. Pour plus d’informations, consultez la vue d’ensemble de la géométrie.

Qu'est-ce qu'une animation de chemin ?

Une animation de parcours est un type de AnimationTimeline qui utilise PathGeometry comme entrée. Au lieu de définir une propriété From, To ou By (comme c'est le cas pour une animation From/To/By) ou d’utiliser des images clés (comme pour une animation par image-clé), vous définissez un chemin géométrique et l'utilisez pour définir la propriété PathGeometry de l’animation de chemin. À mesure que l’animation de chemin progresse, elle lit les informations x, y et angle du chemin et utilise ces informations pour générer sa sortie.

Les animations de chemin sont très utiles pour animer un objet le long d’un chemin complexe. Une façon de déplacer un objet le long d’un chemin consiste à utiliser un MatrixTransform et un MatrixAnimationUsingPath pour transformer un objet le long d’un chemin complexe. L’exemple suivant illustre cette technique à l’aide de l’objet MatrixAnimationUsingPath pour animer la Matrix propriété d’un MatrixTransform. MatrixTransform est appliqué à un bouton et le fait déplacer le long d’un chemin courbé. Étant donné que la propriété DoesRotateWithTangent est définie sur true, le rectangle pivote le long de la tangente du trajet.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="PresentationOptions" Margin="20">
  <Canvas Width="400" Height="400">
      
    <!-- The Button that is animated across the screen by animating
         the MatrixTransform applied to the button. -->
    <Button MinWidth="100" Content="A Button">
      <Button.RenderTransform>
        <MatrixTransform x:Name="ButtonMatrixTransform">
          <MatrixTransform.Matrix >
            <Matrix />
          </MatrixTransform.Matrix>
        </MatrixTransform>
      </Button.RenderTransform>
      <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Loaded">
          <BeginStoryboard>
            <Storyboard>
              <MatrixAnimationUsingPath
              Storyboard.TargetName="ButtonMatrixTransform"
              Storyboard.TargetProperty="Matrix"
              DoesRotateWithTangent="True"
              Duration="0:0:5" 
              RepeatBehavior="Forever" >
                <MatrixAnimationUsingPath.PathGeometry>
                  <PathGeometry 
                    Figures="M 10,100 C 35,0 135,0 160,100 180,190 285,200 310,100" 
                    PresentationOptions:Freeze="True" />
                </MatrixAnimationUsingPath.PathGeometry>
              </MatrixAnimationUsingPath>
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Button.Triggers>
    </Button>
  </Canvas>
</Page>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SDKSample
{

    /// <summary>
    /// Shows how to animate an object along
    /// a geometric path.
    /// </summary>
    public class MatrixAnimationUsingPathDoesRotateWithTangentExample : Page
    {

        public MatrixAnimationUsingPathDoesRotateWithTangentExample()
        {
            this.Margin = new Thickness(20);

            // Create a NameScope for the page so that
            // we can use Storyboards.
            NameScope.SetNameScope(this, new NameScope());

            // Create a button.
            Button aButton = new Button();
            aButton.MinWidth = 100;
            aButton.Content = "A Button";

            // Create a MatrixTransform. This transform
            // will be used to move the button.
            MatrixTransform buttonMatrixTransform = new MatrixTransform();
            aButton.RenderTransform = buttonMatrixTransform;

            // Register the transform's name with the page
            // so that it can be targeted by a Storyboard.
            this.RegisterName("ButtonMatrixTransform", buttonMatrixTransform);

            // Create a Canvas to contain the button
            // and add it to the page.
            // Although this example uses a Canvas,
            // any type of panel will work.
            Canvas mainPanel = new Canvas();
            mainPanel.Width = 400;
            mainPanel.Height = 400;
            mainPanel.Children.Add(aButton);
            this.Content = mainPanel;

            // Create the animation path.
            PathGeometry animationPath = new PathGeometry();
            PathFigure pFigure = new PathFigure();
            pFigure.StartPoint = new Point(10, 100);
            PolyBezierSegment pBezierSegment = new PolyBezierSegment();
            pBezierSegment.Points.Add(new Point(35, 0));
            pBezierSegment.Points.Add(new Point(135, 0));
            pBezierSegment.Points.Add(new Point(160, 100));
            pBezierSegment.Points.Add(new Point(180, 190));
            pBezierSegment.Points.Add(new Point(285, 200));
            pBezierSegment.Points.Add(new Point(310, 100));
            pFigure.Segments.Add(pBezierSegment);
            animationPath.Figures.Add(pFigure);

            // Freeze the PathGeometry for performance benefits.
            animationPath.Freeze();

            // Create a MatrixAnimationUsingPath to move the
            // button along the path by animating
            // its MatrixTransform.
            MatrixAnimationUsingPath matrixAnimation =
                new MatrixAnimationUsingPath();
            matrixAnimation.PathGeometry = animationPath;
            matrixAnimation.Duration = TimeSpan.FromSeconds(5);
            matrixAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Set the animation's DoesRotateWithTangent property
            // to true so that rotates the rectangle in addition
            // to moving it.
            matrixAnimation.DoesRotateWithTangent = true;

            // Set the animation to target the Matrix property
            // of the MatrixTransform named "ButtonMatrixTransform".
            Storyboard.SetTargetName(matrixAnimation, "ButtonMatrixTransform");
            Storyboard.SetTargetProperty(matrixAnimation,
                new PropertyPath(MatrixTransform.MatrixProperty));

            // Create a Storyboard to contain and apply the animation.
            Storyboard pathAnimationStoryboard = new Storyboard();
            pathAnimationStoryboard.Children.Add(matrixAnimation);

            // Start the storyboard when the button is loaded.
            aButton.Loaded += delegate(object sender, RoutedEventArgs e)
            {
                // Start the storyboard.
                pathAnimationStoryboard.Begin(this);
            };
        }
    }
}

Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports System.Windows.Shapes


Namespace SDKSample

    ''' <summary>
    ''' Shows how to animate an object along
    ''' a geometric path.
    ''' </summary>
    Public Class MatrixAnimationUsingPathDoesRotateWithTangentExample
        Inherits Page

        Public Sub New()
            Me.Margin = New Thickness(20)

            ' Create a NameScope for the page so that
            ' we can use Storyboards.
            NameScope.SetNameScope(Me, New NameScope())

            ' Create a button.
            Dim aButton As New Button()
            aButton.MinWidth = 100
            aButton.Content = "A Button"

            ' Create a MatrixTransform. This transform
            ' will be used to move the button.
            Dim buttonMatrixTransform As New MatrixTransform()
            aButton.RenderTransform = buttonMatrixTransform

            ' Register the transform's name with the page
            ' so that it can be targeted by a Storyboard.
            Me.RegisterName("ButtonMatrixTransform", buttonMatrixTransform)

            ' Create a Canvas to contain the button
            ' and add it to the page.
            ' Although this example uses a Canvas,
            ' any type of panel will work.
            Dim mainPanel As New Canvas()
            mainPanel.Width = 400
            mainPanel.Height = 400
            mainPanel.Children.Add(aButton)
            Me.Content = mainPanel

            ' Create the animation path.
            Dim animationPath As New PathGeometry()
            Dim pFigure As New PathFigure()
            pFigure.StartPoint = New Point(10, 100)
            Dim pBezierSegment As New PolyBezierSegment()
            pBezierSegment.Points.Add(New Point(35, 0))
            pBezierSegment.Points.Add(New Point(135, 0))
            pBezierSegment.Points.Add(New Point(160, 100))
            pBezierSegment.Points.Add(New Point(180, 190))
            pBezierSegment.Points.Add(New Point(285, 200))
            pBezierSegment.Points.Add(New Point(310, 100))
            pFigure.Segments.Add(pBezierSegment)
            animationPath.Figures.Add(pFigure)

            ' Freeze the PathGeometry for performance benefits.
            animationPath.Freeze()

            ' Create a MatrixAnimationUsingPath to move the
            ' button along the path by animating
            ' its MatrixTransform.
            Dim matrixAnimation As New MatrixAnimationUsingPath()
            matrixAnimation.PathGeometry = animationPath
            matrixAnimation.Duration = TimeSpan.FromSeconds(5)
            matrixAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Set the animation's DoesRotateWithTangent property
            ' to true so that rotates the rectangle in addition
            ' to moving it.
            matrixAnimation.DoesRotateWithTangent = True

            ' Set the animation to target the Matrix property
            ' of the MatrixTransform named "ButtonMatrixTransform".
            Storyboard.SetTargetName(matrixAnimation, "ButtonMatrixTransform")
            Storyboard.SetTargetProperty(matrixAnimation, New PropertyPath(MatrixTransform.MatrixProperty))

            ' Create a Storyboard to contain and apply the animation.
            Dim pathAnimationStoryboard As New Storyboard()
            pathAnimationStoryboard.Children.Add(matrixAnimation)

            ' Start the storyboard when the button is loaded.
            AddHandler aButton.Loaded, Sub(sender As Object, e As RoutedEventArgs) pathAnimationStoryboard.Begin(Me)



        End Sub
    End Class
End Namespace

Pour plus d’informations sur la syntaxe de chemin d’accès utilisée dans l’exemple XAML, consultez la vue d’ensemble de la syntaxe de balisage de chemin d’accès . Pour obtenir l'exemple complet, consultez l’Exemple d’Animation de Trajectoire .

Vous pouvez appliquer une animation de trajectoire à une propriété en utilisant un Storyboard dans XAML et le code, ou en utilisant la méthode BeginAnimation dans le code. Vous pouvez également utiliser une animation de chemin d’accès pour créer un AnimationClock et l’appliquer à une ou plusieurs propriétés. Pour plus d’informations sur les différentes méthodes d’application d’animations, consultez Vue d’ensemble des techniques d’animation de propriété.

Types d’animations de trajectoire

Étant donné que les animations génèrent des valeurs de propriété, il existe différents types d’animations pour différents types de propriétés. Pour animer une propriété qui prend une Double (telle que la X propriété d’un TranslateTransform), vous utilisez une animation qui produit des Double valeurs. Pour animer une propriété qui prend un Point, vous utilisez une animation qui produit des Point valeurs, et ainsi de suite.

Les classes d'animation de parcours appartiennent à l'espace de noms System.Windows.Media.Animation et suivent la convention de dénomination suivante :

<Type>AnimationUsingPath

<Type> est le type de valeur animé par la classe.

WPF fournit les classes d'animation de chemin suivantes.

Type de propriété Classe d’animation de chemin correspondant Exemple :
Double DoubleAnimationUsingPath Animer un Objet le long d’une Trajectoire (Double Animation)
Matrix MatrixAnimationUsingPath animer un objet le long d’un chemin (animation par matrice)
Point PointAnimationUsingPath Animer un objet le long d’un trajet (animation de points)

Un MatrixAnimationUsingPath génère des Matrix valeurs à partir de son PathGeometry. Lorsqu’il est utilisé avec un MatrixTransform, un MatrixAnimationUsingPath peut déplacer un objet le long d’un chemin. Si vous définissez la DoesRotateWithTangent propriété sur MatrixAnimationUsingPathtrue, elle fait également pivoter l’objet le long des courbes du chemin.

Un PointAnimationUsingPath génère des Point valeurs à partir des coordonnées x et y de son PathGeometry. En utilisant une PointAnimationUsingPath pour animer une propriété qui prend des valeurs Point, vous pouvez déplacer un objet le long d'un chemin. PointAnimationUsingPath ne peut pas faire pivoter les objets.

Un DoubleAnimationUsingPath génère des Double valeurs à partir de son PathGeometry. En définissant la propriété Source, vous pouvez spécifier si DoubleAnimationUsingPath utilise la coordonnée x, la coordonnée y ou l'angle du chemin comme sortie. Vous pouvez utiliser un DoubleAnimationUsingPath pour faire pivoter un objet ou le déplacer le long de l’axe x ou de l’axe y.

Entrée d’animation de chemin d’accès

Chaque classe d’animation de chemin fournit une PathGeometry propriété pour spécifier son entrée. L’animation de chemin utilise le PathGeometry pour générer ses valeurs de sortie. La PathGeometry classe vous permet de décrire plusieurs figures complexes composées d’arcs, de courbes et de lignes.

Au cœur d'une collection d'objets PathGeometry, ces objets portent ce nom car chaque figure décrit une forme distincte dans le PathFigure. Chacun PathFigure se compose d’un ou PathSegment plusieurs objets, chacun décrivant un segment de la figure.

Il existe de nombreux types de segments.

Type de Segment Descriptif
ArcSegment Crée un arc elliptique entre deux points.
BezierSegment Crée une courbe bezier cubique entre deux points.
LineSegment Crée une ligne entre deux points.
PolyBezierSegment Crée une série de courbes de Bézier cubiques.
PolyLineSegment Crée une série de lignes.
PolyQuadraticBezierSegment Crée une série de courbes de Bezier quadratique.
QuadraticBezierSegment Crée une courbe de Bezier quadratique.

Les segments d’un objet PathFigure sont combinés en une forme géométrique unique, qui utilise le point de fin d’un segment comme point de départ du segment suivant. La propriété StartPoint d’un PathFigure spécifie le point à partir duquel le premier segment est dessiné. Chaque segment suivant commence au point de terminaison du segment précédent. Par exemple, une ligne verticale de 10,50 à 10,150 peut être définie en définissant la propriété StartPoint sur 10,50 et en créant un LineSegment avec un paramètre de propriété Point de 10,150.

Pour plus d’informations sur les objets, consultez la PathGeometry de Geometry.

En XAML, vous pouvez également utiliser une syntaxe abrégée spéciale pour définir la Figures propriété d’un PathGeometry. Pour plus d’informations, consultez la vue d’ensemble de la syntaxe de balisage de chemin d’accès .

Pour plus d’informations sur la syntaxe de chemin d’accès utilisée dans l’exemple XAML, consultez la vue d’ensemble de la syntaxe de balisage de chemin d’accès .

Voir aussi