Share via


Información general sobre animaciones en trazados

En este tema se ofrece una introducción a las animaciones de trazado, que permiten usar un trazado geométrico para generar valores de salida. Las animaciones de trazado son útiles para mover y girar los objetos a lo largo de trayectorias complejas.

Requisitos previos

Para entender este tema, debe estar familiarizado con las características de animación de WPF. Para obtener una introducción a las características de animación, vea Información general sobre animaciones.

Dado que usa un objeto PathGeometry para definir una animación de trazado, también debería estar familiarizado con PathGeometry y los distintos tipos de objetos PathSegment. Para obtener más información, vea Información general sobre geometría.

¿Qué es una animación de trazado?

Una animación de trazado es un tipo de AnimationTimeline que usa un objeto PathGeometry como entrada. En lugar de establecer una propiedad From, To o By (como sucedería en el caso de una animación From/To/By) o usar fotogramas clave (como sucedería en el caso de una animación de fotograma clave), define un trazado geométrico y lo usa para establecer la propiedad PathGeometry de la animación de trazado. A medida que la animación de trazado avanza, lee la información de ángulo, X e Y del trazado y usa esa información para generar sus resultados.

Las animaciones de trazado son muy útiles para animar un objeto a lo largo de una trayectoria compleja. Una manera de mover un objeto a lo largo de una trayectoria es usar MatrixTransform y MatrixAnimationUsingPath para transformar un objeto a lo largo de una trayectoria compleja. En el ejemplo siguiente se demuestra esta técnica mediante el uso del objeto MatrixAnimationUsingPath para animar la propiedad Matrix de MatrixTransform. MatrixTransform se aplica a un botón y hace que se mueva a lo largo de un trazado curvo. Dado que la propiedad DoesRotateWithTangent está establecida en true, el rectángulo gira a lo largo de la tangente del trazado.

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



        }  
    }
}

Para obtener más información sobre la sintaxis de trazado que se usa en el ejemplo de XAML, vea la información general que se incluye en Sintaxis de marcado de trazados. Para obtener el ejemplo completo, vea Ejemplo Path Animation.

Puede aplicar una animación de trazado a una propiedad mediante el uso de un Storyboard en XAML y código, o bien mediante el uso del método BeginAnimation en el código. También puede usar una animación de trazado para crear AnimationClock y aplicarla a una o más propiedades. Para obtener más información sobre los distintos métodos para aplicar animaciones, vea Información general sobre técnicas de animación de propiedades.

Tipos de animación de trazado

Dado que las animaciones generan valores de propiedades, hay distintos tipos de animaciones para los diversos tipos de propiedades. Para animar una propiedad que acepta un valor Double (como la propiedad X de TranslateTransform), se usa una animación que genera valores Double. Para animar una propiedad que acepta una estructura Point, se usa una animación que genera valores Point, y así sucesivamente.

Las clases de animaciones de trazado pertenecen al espacio de nombres System.Windows.Media.Animation y usan la convención de nomenclatura siguiente:

*<Tipo>*AnimationUsingPath

Donde <Tipo> es el tipo de valor que la clase anima.

WPF proporciona las clases de animación de trazado siguientes.

Tipo de propiedad

Clase de animación de trazado correspondiente

Ejemplo

Double

DoubleAnimationUsingPath

Cómo: Animar un objeto a lo largo de una trayectoria (animación doble)

Matrix

MatrixAnimationUsingPath

Cómo: Animar un objeto a lo largo de una trayectoria (animación de matriz)

Point

PointAnimationUsingPath

Cómo: Animar un objeto a lo largo de un trazado (animación en punto)

MatrixAnimationUsingPath genera valores de Matrix a partir de su PathGeometry. Cuando se usa con MatrixTransform, MatrixAnimationUsingPath puede mover un objeto a lo largo de una trayectoria. Si establece la propiedad DoesRotateWithTangent de MatrixAnimationUsingPath en true, también gira el objeto a lo largo de las curvas de la trayectoria.

PointAnimationUsingPath genera valores Point a partir de las coordenadas X e Y de su PathGeometry. Al usar PointAnimationUsingPath para animar una propiedad que acepta valores Point, puede mover un objeto a lo largo de una trayectoria. PointAnimationUsingPath no puede girar objetos.

DoubleAnimationUsingPath genera valores Double a partir de su PathGeometry. Al establecer la propiedad Source, puede especificar si DoubleAnimationUsingPath usa la coordenada X, la coordenada Y o el ángulo del trazado como salida. Puede usar DoubleAnimationUsingPath para girar un objeto o moverlo a lo largo del eje X o Y.

Entrada de animación de trazado

Cada clase de animación de trazado proporciona una propiedad PathGeometry para especificar su entrada. La animación de trazado usa PathGeometry para generar sus valores de salida. La clase PathGeometry permite describir varias figuras complejas que se componen de arcos, curvas y líneas.

En el núcleo de PathGeometry hay una colección de objetos PathFigure; estos objetos se denominan así porque cada figura describe una forma discreta de PathGeometry. Cada PathFigure se compone de uno o varios objetos PathSegment, cada uno de los cuales describe un segmento de la figura.

Existen muchos tipos de segmentos.

Tipo de segmento

Descripción

ArcSegment

Crea un arco elíptico entre dos puntos.

BezierSegment

Crea una curva Bézier cúbica entre dos puntos.

LineSegment

Crea una línea entre dos puntos.

PolyBezierSegment

Crea una serie de curvas Bézier cúbicas.

PolyLineSegment

Crea una serie de líneas.

PolyQuadraticBezierSegment

Crea una serie de curvas Bézier cuadráticas.

QuadraticBezierSegment

Crea una curva Bézier cuadrática.

Los segmentos de PathFigure se combinan en una sola forma geométrica que usa el punto final de un segmento como el punto inicial del segmento siguiente. La propiedad StartPoint de PathFigure especifica el punto desde el que se dibuja el primer segmento. Cada segmento posterior comienza en el punto final del segmento anterior. Por ejemplo, para definir una línea vertical de 10,50 a 10,150 se establece la propiedad StartPoint en 10,50 y se crea un LineSegment con un valor de 10,150 para la propiedad Point.

Para obtener más información acerca de los objetos PathGeometry, consulte Información general sobre geometría.

En XAML, puede utilizar también una sintaxis abreviada especial para establecer la propiedad Figures de PathGeometry. Para obtener más información, lea la información general de Sintaxis de marcado de trazados.

Para obtener más información sobre la sintaxis de trazado que se usa en el ejemplo de XAML, lea la información general de Sintaxis de marcado de trazados.

Vea también

Conceptos

Sintaxis de marcado de trazados

Información general sobre animaciones

Información general sobre técnicas de animación de propiedades

Otros recursos

Ejemplo Path Animation

Temas "Cómo..." de animación de trazado