Panoramica sulle animazioni tracciato

Questo argomento presenta le animazioni tracciato, che consentono di usare un tracciato geometrico per generare valori di output. Le animazioni tracciato sono utili per lo spostamento e rotazione di oggetti lungo tracciati complessi.

Prerequisiti

Per comprendere questo argomento, è necessario avere familiarità con le funzionalità delle animazioni WPF. Per un'introduzione alle funzionalità di animazione, vedere Cenni preliminari sull'animazione.

Poiché usi un oggetto per definire un'animazione PathGeometry di percorso, dovresti anche avere familiarità con PathGeometry i diversi tipi di PathSegment oggetti. Per altre informazioni, vedere Cenni preliminari sulle classi Geometry.

Che cos'è un'animazione tracciato?

Un'animazione di percorso è un tipo di AnimationTimeline che usa come PathGeometry input. Invece di impostare una proprietà From, To o By (come fai per un'animazione From/To/By) o usando fotogrammi chiave (come usi per un'animazione con fotogrammi chiave), definisci un percorso geometrico e lo usi per impostare la PathGeometry proprietà dell'animazione del percorso. Con l'avanzamento dell'animazione tracciato, le informazioni relative a x, y e all'angolo vengono lette dal tracciato e usate per generare l'output.

Le animazioni tracciato sono estremamente utili per aggiungere un'animazione a un oggetto lungo un tracciato complesso. Un modo per spostare un oggetto lungo un percorso consiste nell'usare un MatrixTransform oggetto e un MatrixAnimationUsingPath oggetto per trasformare un oggetto lungo un percorso complesso. Nell'esempio seguente viene illustrata questa tecnica utilizzando l'oggetto MatrixAnimationUsingPath per animare la Matrix proprietà di un oggetto MatrixTransform. L'oggetto MatrixTransform viene applicato a un pulsante e ne determina lo spostamento lungo un percorso curvo. Poiché la DoesRotateWithTangent proprietà è impostata su true, il rettangolo ruota lungo la tangente del percorso.

<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

Per altre informazioni sulla sintassi del percorso usata nell'esempio XAML, vedere La panoramica della sintassi di markup del percorso. Per l'esempio completo, vedere Path Animation Sample (Esempio di animazione tracciato).

Puoi applicare un'animazione del percorso a una proprietà usando un Storyboard oggetto in XAML e codice oppure usando il BeginAnimation metodo nel codice. È anche possibile usare un'animazione di percorso per creare un oggetto e applicarlo AnimationClock a una o più proprietà. Per altre informazioni sui diversi metodi per l'applicazione di animazioni, vedere Cenni preliminari sulle tecniche di animazione delle proprietà.

Tipi di animazione tracciato

Poiché le animazioni generano valori di proprietà, esistono diversi tipi di animazione per i diversi tipi di proprietà. Per animare una proprietà che accetta , Double ad esempio la X proprietà di un TranslateTransformoggetto , si usa un'animazione che produce Double valori. Per animare una proprietà che accetta un Pointoggetto , si usa un'animazione che produce Point valori e così via.

Le classi di animazione path appartengono allo spazio dei System.Windows.Media.Animation nomi e usano la convenzione di denominazione seguente:

<Type>AnimationUsingPath

Dove <Type> è il tipo di valore a cui viene animata la classe .

WPF fornisce le classi di animazione del percorso seguenti.

Tipo di proprietà Classe di animazione tracciato corrispondente Esempio
Double DoubleAnimationUsingPath Animare un oggetto lungo un tracciato (animazione Double)
Matrix MatrixAnimationUsingPath Animare un oggetto lungo un tracciato (animazione Matrix)
Point PointAnimationUsingPath Animare un oggetto lungo un tracciato (animazione Point)

Un MatrixAnimationUsingPath oggetto genera Matrix valori dal relativo PathGeometryoggetto . Se usato con , MatrixTransformun MatrixAnimationUsingPath oggetto può spostare un oggetto lungo un percorso. Se si imposta la DoesRotateWithTangent proprietà di MatrixAnimationUsingPath su true, ruota anche l'oggetto lungo le curve del percorso.

Un PointAnimationUsingPath oggetto genera Point valori dalle coordinate x e y del relativo PathGeometryoggetto . Utilizzando un PointAnimationUsingPath oggetto per animare una proprietà che accetta Point valori, è possibile spostare un oggetto lungo un percorso. Un PointAnimationUsingPath oggetto non può ruotare gli oggetti.

Un DoubleAnimationUsingPath oggetto genera Double valori dal relativo PathGeometryoggetto . Impostando la Source proprietà, è possibile specificare se DoubleAnimationUsingPath usa la coordinata x, la coordinata y o l'angolo del percorso come output. È possibile utilizzare un oggetto DoubleAnimationUsingPath per ruotare un oggetto o spostarlo lungo l'asse x o l'asse y.

Input dell'animazione tracciato

Ogni classe di animazione del percorso fornisce una PathGeometry proprietà per specificarne l'input. L'animazione del percorso usa per PathGeometry generare i valori di output. La PathGeometry classe consente di descrivere più figure complesse composte da archi, curve e linee.

Al centro di un PathGeometry oggetto è una raccolta di PathFigure oggetti. Questi oggetti sono così denominati perché ogni figura descrive una forma discreta nell'oggetto PathGeometry. Ognuno PathFigure è costituito da uno o più PathSegment oggetti, ognuno dei quali descrive un segmento della figura.

Esistono diversi tipi di segmenti.

Tipo di segmento Descrizione
ArcSegment Crea un arco ellittico tra due punti.
BezierSegment Crea una curva di Bézier cubica tra due punti.
LineSegment Crea una linea tra due punti.
PolyBezierSegment Crea una serie di curve di Bézier cubiche.
PolyLineSegment Crea una serie di linee.
PolyQuadraticBezierSegment Crea una serie di curve di Bézier quadratiche.
QuadraticBezierSegment Crea una curva di Bézier quadratica.

I segmenti di un PathFigure oggetto vengono combinati in una singola forma geometrica, che utilizza il punto finale di un segmento come punto iniziale del segmento successivo. La StartPoint proprietà di un PathFigure oggetto specifica il punto da cui viene disegnato il primo segmento. Ogni segmento successivo inizia in corrispondenza del punto finale del segmento precedente. Ad esempio, una linea verticale da 10,50 a 10,150 può essere definita impostando la StartPoint proprietà su 10,50 e creando un LineSegment oggetto con un'impostazione Point di proprietà di 10,150.

Per altre informazioni sugli PathGeometry oggetti, vedere Cenni preliminari sulla geometria.

In XAML puoi anche usare una sintassi abbreviata speciale per impostare la Figures proprietà di un oggetto PathGeometry. Per altre informazioni, vedere i cenni preliminari sulla Sintassi di markup del tracciato.

Per altre informazioni sulla sintassi del percorso usata nell'esempio XAML, vedere La panoramica della sintassi di markup del percorso.

Vedi anche