Share via


Vue d'ensemble des animations de tracés

Cette rubrique présente des animations de tracé qui vous permettent d'utiliser un tracé géométrique pour générer des valeurs de sortie. Les animations de tracé sont utiles pour déplacer et faire pivoter des objets sur des tracés complexes.

Composants requis

Pour comprendre cette rubrique, vous devez être familiarisé avec les fonctionnalités d'animations WPF. Pour une introduction aux fonctionnalités d'animation, consultez Vue d'ensemble de l'animation.

Étant donné que vous utilisez un objet PathGeometry pour définir une animation de tracé, vous devez également être familiarisé avec PathGeometry et les différents types d'objets PathSegment. Pour plus d'informations, consultez Vue d'ensemble de Geometry.

Qu'est-ce qu'une animation de tracé ?

Une animation de tracé est un type de AnimationTimeline qui utilise un PathGeometry comme entrée. Au lieu de définir une propriété De, À ou Par (comme vous le faites pour une animation From/To/By) ou d'utiliser des images clés (comme vous le faites pour une animation d'image clé), définissez un tracé géométrique et utilisez-le pour définir la propriété PathGeometry de l'animation de tracé. Pendant sa progression, l'animation de tracé lit les informations x, y et les informations d'angle du tracé, puis elle les utilise pour générer sa sortie.

Les animations de tracé sont très utiles pour animer un objet sur un tracé complexe. L'une des manières de déplacer un objet sur un tracé est d'utiliser un MatrixTransform et un MatrixAnimationUsingPath pour transformer un objet sur un tracé complexe. L'exemple suivant montre cette technique à l'aide de l'objet MatrixAnimationUsingPath pour animer la propriété Matrix d'un MatrixTransform. Le MatrixTransform est appliqué à un bouton et permet de le déplacer sur un tracé courbé. Étant donné que la propriété DoesRotateWithTangent a la valeur true, le rectangle pivote sur la tangente du tracé.

<Page 
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
  xmlns:PresentationOptions="https://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="https://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>

Imports System
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
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);
            };



        }  
    }
}

Pour plus d'informations sur la syntaxe de tracé utilisée dans l'exemple XAML, consultez la vue d'ensemble Syntaxe XAML pour les tracés. Pour l'exemple complet, consultez Animation de tracé, exemple (page éventuellement en anglais).

Vous pouvez appliquer une animation de tracé à une propriété à l'aide d'un Storyboard en XAML et dans du code, ou dans le code à l'aide de la méthode BeginAnimation. Vous pouvez également utiliser une animation de tracé 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 des animations, consultez Vue d'ensemble des techniques d'animation de propriétés.

Types d'animations de tracé

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

Les classes d'animation de tracé appartiennent à l'espace de noms System.Windows.Media.Animation et utilisent la convention d'affectation de noms suivante :

*<Type>*AnimationUsingPath

<Type> est le type de valeur que la classe anime.

WPF fournit les classes d'animation de tracé suivantes.

Type de propriété

Classe d'animation de tracé correspondante

Exemple

Double

DoubleAnimationUsingPath

Comment : animer un objet sur un tracé (animation double)

Matrix

MatrixAnimationUsingPath

Comment : animer un objet sur un tracé (animation de matrice)

Point

PointAnimationUsingPath

Comment : animer un objet sur un tracé (animation de point)

Un MatrixAnimationUsingPath génère des valeurs Matrix à partir de son PathGeometry. Lorsqu'il est utilisé avec un MatrixTransform, un MatrixAnimationUsingPath peut déplacer un objet sur un tracé. Si vous affectez à la propriété DoesRotateWithTangent du MatrixAnimationUsingPath la valeur true, il fait également pivoter l'objet sur les courbes du tracé.

Un PointAnimationUsingPath génère des valeurs Point depuis les coordonnées x et y de son PathGeometry. En utilisant un PointAnimationUsingPath pour animer une propriété qui accepte les valeurs Point, vous pouvez déplacer un objet sur un tracé. Un PointAnimationUsingPath ne peut pas faire pivoter des objets.

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

Entrée de l'animation de tracé

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

Au cœur d'un PathGeometry, on trouve une collection d'objets PathFigure : ils s'appellent ainsi car chaque illustration décrit une forme discrète du PathGeometry. Chaque PathFigure se compose d'un ou plusieurs objets PathSegment décrivant chacun un segment de l'illustration.

Il existe de nombreux types de segments.

Type de segment

Description

ArcSegment

Crée un arc elliptique entre deux points.

BezierSegment

Crée une courbe de Bézier 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 Bézier quadratiques.

QuadraticBezierSegment

Crée une courbe de Bézier quadratique.

Les segments d'un PathFigure sont regroupés dans une forme géométrique unique qui utilise le point de terminaison d'un segment comme point de départ du segment suivant. La propriété StartPoint d'un PathFigure spécifie le point depuis lequel le premier segment est dessiné. Chaque segment suivant démarre au point de terminaison du segment précédent. Par exemple, une ligne verticale de 10,50 à 10,150 peut être définie en affectant à la propriété StartPoint la valeur 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 PathGeometry, consultez Vue d'ensemble de Geometry.

En XAML, vous pouvez également utiliser une syntaxe abrégée spéciale pour définir la propriété Figures d'un PathGeometry. Pour plus d'informations, consultez la vue d'ensemble Syntaxe XAML pour les tracés.

Pour plus d'informations sur la syntaxe de tracé utilisée dans l'exemple XAML, consultez la vue d'ensemble Syntaxe XAML pour les tracés.

Voir aussi

Concepts

Syntaxe XAML pour les tracés

Vue d'ensemble de l'animation

Vue d'ensemble des techniques d'animation de propriétés

Autres ressources

Animation de tracé, exemple (page éventuellement en anglais)

Rubriques "Comment" relatives aux animations de tracés