Visão geral de animações do caminho

Este tópico apresenta animações de caminho, que permitem que você use um caminho geométrico para gerar valores de saída. Animações de caminho são úteis para mover e girar objetos junto em caminhos complexos.

Pré-requisitos

Para entender este tópico, você deve estar familiarizado com os recursos de animações do WPF. Para obter uma introdução aos recursos de animações, consulte a Visão geral da animação.

Como você usa um PathGeometry objeto para definir uma animação de caminho, você também deve estar familiarizado com PathGeometry e os diferentes tipos de PathSegment objetos. Para obter mais informações, consulte Visão geral de geometria.

O que é uma animação de caminho?

Uma animação de caminho é um tipo de AnimationTimeline que usa um PathGeometry como entrada. Em vez de definir uma propriedade De, Para ou Por (como faz para uma animação De/Para/Por) ou usar quadros-chave (como você usa para uma animação de quadro-chave), defina um caminho geométrico e use-o para definir a PathGeometry propriedade da animação de caminho. Conforme a animação de caminho progride, ela lê x, y e informações de ângulo do caminho e usa essas informações para gerar a saída.

Animações de caminho são muito úteis para animar um objeto ao longo de um caminho complexo. Uma maneira de mover um objeto ao longo de um caminho é usar a e a MatrixTransformMatrixAnimationUsingPath para transformar um objeto ao longo de um caminho complexo. O exemplo a seguir demonstra essa técnica usando o MatrixAnimationUsingPath objeto para animar a Matrix propriedade de um MatrixTransformarquivo . O MatrixTransform é aplicado a um botão e faz com que ele se mova ao longo de um caminho curvo. Como a DoesRotateWithTangent propriedade é definida como true, o retângulo gira ao longo da tangente do caminho.

<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

Para obter mais informações sobre a sintaxe de caminho usada no exemplo XAML, consulte a Visão geral da sintaxe de marcação de caminho. Para ver o exemplo completo, consulte Exemplo de animação de caminho.

Você pode aplicar uma animação de caminho a uma propriedade usando um Storyboard em XAML e código, ou usando o BeginAnimation método em código. Você também pode usar uma animação de caminho para criar um AnimationClock e aplicá-lo a uma ou mais propriedades. Para obter mais informações sobre os diferentes métodos para aplicação de animações, consulte a Visão geral das técnicas de animação de propriedades.

Tipos de animação de caminho

Como as animações geram valores de propriedade, existem diferentes tipos de animação para diferentes tipos de propriedades. Para animar uma propriedade que usa um (como a X propriedade de um DoubleTranslateTransform), use uma animação que produz Double valores. Para animar uma propriedade que usa um Point, use uma animação que produz Point valores e assim por diante.

As classes de animação de caminho pertencem ao System.Windows.Media.Animation namespace e usam a seguinte convenção de nomenclatura:

<Tipo>AnimationUsingPath

Onde <Type> é o tipo de valor que a classe anima.

O WPF fornece as seguintes classes de animação de caminho.

Tipo de propriedade Classe de animação de caminho correspondente Exemplo
Double DoubleAnimationUsingPath Animar um objeto ao longo de um caminho (animação dupla)
Matrix MatrixAnimationUsingPath Animar um objeto ao longo de um caminho (animação de matriz)
Point PointAnimationUsingPath Animar um objeto ao longo de um caminho (animação de ponto)

A MatrixAnimationUsingPath gera Matrix valores a partir de seu PathGeometry. Quando usado com um , um pode mover um objeto ao longo de um MatrixTransformMatrixAnimationUsingPath caminho. Se você definir a DoesRotateWithTangent propriedade do para true, ele também girará o objeto ao longo das curvas do MatrixAnimationUsingPath caminho.

A PointAnimationUsingPath gera Point valores a partir das coordenadas x e y de seu PathGeometry. Usando um para animar uma propriedade que recebe Point valores, você pode mover um objeto ao longo de um PointAnimationUsingPath caminho. A PointAnimationUsingPath não pode girar objetos.

A DoubleAnimationUsingPath gera Double valores a partir de seu PathGeometry. Ao definir a propriedade, você pode especificar se o usa a coordenada x, a Source coordenada y ou o DoubleAnimationUsingPath ângulo do caminho como saída. Você pode usar um para girar um DoubleAnimationUsingPath objeto ou movê-lo ao longo do eixo x ou eixo y.

Entrada de animação de caminho

Cada classe de animação de caminho fornece uma PathGeometry propriedade para especificar sua entrada. A animação de caminho usa o para gerar seus valores de PathGeometry saída. A PathGeometry classe permite descrever várias figuras complexas que são compostas de arcos, curvas e linhas.

No coração de um PathGeometry está uma coleção de PathFigure objetos, esses objetos são assim chamados porque cada figura descreve uma forma discreta no PathGeometry. Cada PathFigure um consiste em um ou mais PathSegment objetos, cada um dos quais descreve um segmento da figura.

Há muitos tipos de segmentos.

Tipo de segmento Descrição
ArcSegment Cria um arco elíptico entre dois pontos.
BezierSegment Cria uma curva de Bézier cúbica entre dois pontos.
LineSegment Cria uma linha entre dois pontos.
PolyBezierSegment Cria uma série de curvas de Bézier cúbicas.
PolyLineSegment Cria uma série de linhas.
PolyQuadraticBezierSegment Cria uma série de curvas de Bézier quadráticas.
QuadraticBezierSegment Cria uma curva de Bezier quadrática.

Os segmentos em um são combinados em uma única forma geométrica, que usa o ponto final de um PathFigure segmento como o ponto inicial do próximo segmento. A StartPoint propriedade de a especifica o ponto a PathFigure partir do qual o primeiro segmento é desenhado. Cada segmento subsequente começa no ponto de extremidade do segmento anterior. Por exemplo, uma linha vertical de para 10,150 pode ser definida definindo a StartPoint propriedade como 10,50 e criando uma configuração com uma PointLineSegment propriedade de 10,5010,150.

Para obter mais informações sobre PathGeometry objetos, consulte a Visão geral da geometria.

Em XAML, você também pode usar uma sintaxe abreviada especial para definir a Figures propriedade de um PathGeometryarquivo . Para obter mais informações, consulte a visão geral de Sintaxe de marcação de caminho.

Para obter mais informações sobre a sintaxe de caminho usada no exemplo XAML, consulte a Visão geral da sintaxe de marcação de caminho.

Confira também