Visão geral das técnicas de animação da propriedade

Este tópico descreve as diferentes abordagens para animar propriedades: storyboards, animações locais, relógios e animações por quadro.

Pré-requisitos

Para entender este tópico, você deve estar familiarizado com os recursos básicos de animação descritos na Visão geral da animação.

Diferentes maneiras de animar

Como há muitos cenários diferentes para animar propriedades, o WPF fornece várias abordagens para animar propriedades.

Para cada abordagem, a tabela a seguir indica se ela pode ser usada por instância, em estilos, em modelos de controle ou em modelos de dados; se ele pode ser usado em XAML; e se a abordagem permite controlar interativamente a animação. "Por instância" se refere à técnica de aplicar uma animação ou storyboard diretamente às instâncias de um objeto, em vez de um estilo, modelo de controle ou modelo de dados.

Técnica de animação Cenários Dá suporte a XAML Controlável interativamente
Animação de storyboard Por instância, , , StyleControlTemplateDataTemplate Sim Yes
Animação local Por instância Não Não
Animação de relógio Por instância Não Sim
Animação por quadro Por instância Não N/D

Animações de storyboard

Use um quando quiser definir e aplicar suas animações em XAML, controlar interativamente suas animações depois que elas forem iniciadas, criar uma árvore complexa de animações ou animar em um StoryboardStyle, ControlTemplate ou DataTemplate. Para que um objeto seja animado por um , ele deve ser um ou , ou deve ser usado para definir um StoryboardFrameworkElementFrameworkElement ou .FrameworkContentElementFrameworkContentElement Para obter mais detalhes, consulte a Visão geral de storyboards.

A Storyboard é um tipo especial de contêiner Timeline que fornece informações de direcionamento para as animações que ele contém. Para animar com um Storyboard, conclua as três etapas a seguir.

  1. Declare uma e uma Storyboard ou mais animações.

  2. Use as propriedades e anexadas TargetName para especificar o objeto de destino e TargetProperty a propriedade de cada animação.

  3. (Somente código) Defina um NameScope foro FrameworkElement ou FrameworkContentElement. Registre os nomes dos objetos a serem animados com esse FrameworkElement ou FrameworkContentElement.

  4. Comece o Storyboardarquivo .

Iniciar um Storyboard aplica animações às propriedades que elas animam e as inicia. Há duas maneiras de começar um Storyboard: você pode usar o Begin método fornecido pela Storyboard classe ou pode usar uma BeginStoryboard ação. A única maneira de animar em XAML é usar uma BeginStoryboard ação. Uma BeginStoryboard ação pode ser usada em uma EventTriggerpropriedade Trigger, ou em um DataTriggerarquivo .

A tabela a seguir mostra os diferentes locais onde cada Storyboard técnica de início é suportada: por instância, estilo, modelo de controle e modelo de dados.

O storyboard é iniciado usando… Por instância Estilo Modelo de controle Modelo de dados Exemplo
BeginStoryboard e um EventTrigger Sim Sim Sim Yes Animar uma propriedade usando um storyboard
BeginStoryboard e um imóvel Trigger Não Sim Sim Yes Disparar uma animação quando o valor de uma propriedade é alterado
BeginStoryboard e um DataTrigger Não Sim Sim Yes Como disparar uma animação quando dados são alterados
Método Begin Sim No No Não Animar uma propriedade usando um storyboard

Para obter mais informações sobre Storyboard objetos, consulte a Visão geral de storyboards.

Animações locais

As animações locais fornecem uma maneira conveniente de animar uma propriedade de dependência de qualquer Animatable objeto. Use animações locais quando você quiser aplicar uma única animação a uma propriedade e não precisar controlar interativamente a animação após seu início. Ao contrário de uma animação, uma Storyboard animação local pode animar um objeto que não está associado a um ou a um FrameworkElementFrameworkContentElementarquivo . Você também não precisa definir um NameScope para esse tipo de animação.

Animações locais só podem ser usadas no código e não podem ser definidas em estilos, modelos de controle ou modelos de dados. Uma animação local não pode ser controlada interativamente após ter sido iniciada.

Para animar usando um animação local, conclua as etapas a seguir.

  1. Crie um objeto AnimationTimeline.

  2. Use o BeginAnimation método do objeto que você deseja animar para aplicar o AnimationTimeline à propriedade especificada.

O exemplo a seguir mostra como animar a largura e a cor do plano de fundo de um Buttonarquivo .

/*

   This sample demonstrates how to apply non-storyboard animations to a property.
   To animate in markup, you must use storyboards.

*/

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Navigation;
using namespace System::Windows::Media;
using namespace System::Windows::Media::Animation;
using namespace System::Windows::Shapes;
using namespace System::Windows::Controls;


namespace Microsoft {
   namespace Samples {
      namespace Animation {
         namespace LocalAnimations {
            // Create the demonstration.
            public ref class LocalAnimationExample : Page {

            public: 
               LocalAnimationExample ()
               {
                  WindowTitle = "Local Animation Example";
                  StackPanel^ myStackPanel = gcnew StackPanel();
                  myStackPanel->Margin = Thickness(20);

                  // Create and set the Button.
                  Button^ aButton = gcnew Button();
                  aButton->Content = "A Button";

                  // Animate the Button's Width.
                  DoubleAnimation^ myDoubleAnimation = gcnew DoubleAnimation();
                  myDoubleAnimation->From = 75;
                  myDoubleAnimation->To = 300;
                  myDoubleAnimation->Duration = Duration(TimeSpan::FromSeconds(5));
                  myDoubleAnimation->AutoReverse = true;
                  myDoubleAnimation->RepeatBehavior = RepeatBehavior::Forever;

                  // Apply the animation to the button's Width property.
                  aButton->BeginAnimation(Button::WidthProperty, myDoubleAnimation);

                  // Create and animate a Brush to set the button's Background.
                  SolidColorBrush^ myBrush = gcnew SolidColorBrush();
                  myBrush->Color = Colors::Blue;

                  ColorAnimation^ myColorAnimation = gcnew ColorAnimation();
                  myColorAnimation->From = Colors::Blue;
                  myColorAnimation->To = Colors::Red;
                  myColorAnimation->Duration = Duration(TimeSpan::FromMilliseconds(7000));
                  myColorAnimation->AutoReverse = true;
                  myColorAnimation->RepeatBehavior = RepeatBehavior::Forever;

                  // Apply the animation to the brush's Color property.
                  myBrush->BeginAnimation(SolidColorBrush::ColorProperty, myColorAnimation);
                  aButton->Background = myBrush;

                  // Add the Button to the panel.
                  myStackPanel->Children->Add(aButton);
                  this->Content = myStackPanel;
               };
            };
         }
      }
   }
}
/*

   This sample demonstrates how to apply non-storyboard animations to a property.
   To animate in markup, you must use storyboards.

*/

using System;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls;

namespace Microsoft.Samples.Animation.LocalAnimations
{

    // Create the demonstration.
    public class LocalAnimationExample : Page
    {

        public LocalAnimationExample()
        {

            WindowTitle = "Local Animation Example";
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Margin = new Thickness(20);

            // Create and set the Button.
            Button aButton = new Button();
            aButton.Content = "A Button";

            // Animate the Button's Width.
            DoubleAnimation myDoubleAnimation = new DoubleAnimation();
            myDoubleAnimation.From = 75;
            myDoubleAnimation.To = 300;
            myDoubleAnimation.Duration =  new Duration(TimeSpan.FromSeconds(5));
            myDoubleAnimation.AutoReverse = true;
            myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Apply the animation to the button's Width property.
            aButton.BeginAnimation(Button.WidthProperty, myDoubleAnimation);

            // Create and animate a Brush to set the button's Background.
            SolidColorBrush myBrush = new SolidColorBrush();
            myBrush.Color = Colors.Blue;

            ColorAnimation myColorAnimation = new ColorAnimation();
            myColorAnimation.From = Colors.Blue;
            myColorAnimation.To = Colors.Red;
            myColorAnimation.Duration =  new Duration(TimeSpan.FromMilliseconds(7000));
            myColorAnimation.AutoReverse = true;
            myColorAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Apply the animation to the brush's Color property.
            myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation);
            aButton.Background = myBrush;

            // Add the Button to the panel.
            myStackPanel.Children.Add(aButton);
            this.Content = myStackPanel;
        }
    }
}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''This sample demonstrates how to apply non-storyboard animations to a property.
'''To animate in markup, you must use storyboards.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

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

Namespace Microsoft.Samples.Animation.LocalAnimations

    ' Create the demonstration.
    Public Class LocalAnimationExample
        Inherits Page

        Public Sub New()

            WindowTitle = "Animate Property Example"
            Dim myStackPanel As New StackPanel()
            myStackPanel.Margin = New Thickness(20)

            ' Create and set the Button.
            Dim aButton As New Button()
            aButton.Content = "A Button"

            ' Animate the Button's Width.
            Dim myDoubleAnimation As New DoubleAnimation()
            myDoubleAnimation.From = 75
            myDoubleAnimation.To = 300
            myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
            myDoubleAnimation.AutoReverse = True
            myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Apply the animation to the button's Width property.
            aButton.BeginAnimation(Button.WidthProperty, myDoubleAnimation)

            ' Create and animate a Brush to set the button's Background.
            Dim myBrush As New SolidColorBrush()
            myBrush.Color = Colors.Blue

            Dim myColorAnimation As New ColorAnimation()
            myColorAnimation.From = Colors.Blue
            myColorAnimation.To = Colors.Red
            myColorAnimation.Duration = New Duration(TimeSpan.FromMilliseconds(7000))
            myColorAnimation.AutoReverse = True
            myColorAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Apply the animation to the brush's Color property.
            myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation)
            aButton.Background = myBrush

            ' Add the Button to the panel.
            myStackPanel.Children.Add(aButton)
            Me.Content = myStackPanel
        End Sub
    End Class
End Namespace

Animações de relógio

Use Clock objetos quando quiser animar sem usar um Storyboard e quiser criar árvores de tempo complexas ou controlar animações interativamente depois que elas forem iniciadas. Você pode usar objetos Clock para animar uma propriedade de dependência de qualquer Animatable objeto.

Não é possível usar Clock objetos diretamente para animar em estilos, modelos de controle ou modelos de dados. (O sistema de animação e temporização realmente usa Clock objetos para animar em estilos, modelos de controle e modelos de dados, mas ele deve criar esses Clock objetos para você a partir de um Storyboardarquivo . Para obter mais informações sobre a relação entre Storyboard objetos e objetos, consulte a Visão geral do sistema de animação e Clock temporização.)

Para aplicar um único Clock a uma propriedade, conclua as etapas a seguir.

  1. Crie um objeto AnimationTimeline.

  2. Use o CreateClock método do AnimationTimeline para criar um AnimationClockarquivo .

  3. Use o ApplyAnimationClock método do objeto que você deseja animar para aplicar o AnimationClock à propriedade especificada.

O exemplo a seguir mostra como criar um AnimationClock e aplicá-lo a duas propriedades semelhantes.

/*
    This example shows how to create and apply
    an AnimationClock.
*/

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace Microsoft.Samples.Animation.TimingBehaviors
{
    public class AnimationClockExample : Page
    {

        ScaleTransform myScaleTransform;

        public AnimationClockExample()
        {

            this.WindowTitle = "Opacity Animation Example";
            this.Background = Brushes.White;
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Margin = new Thickness(20);

            // Create a button that with a ScaleTransform.
            // The ScaleTransform will animate when the
            // button is clicked.
            Button myButton = new Button();
            myButton.Margin = new Thickness(50);
            myButton.HorizontalAlignment = HorizontalAlignment.Left;
            myButton.Content = "Click Me";
            myScaleTransform = new ScaleTransform(1,1);
            myButton.RenderTransform = myScaleTransform;

            // Associate an event handler with the
            // button's Click event.
            myButton.Click += new RoutedEventHandler(myButton_Clicked);

            myStackPanel.Children.Add(myButton);
            this.Content = myStackPanel;
        }

        // Create and apply and animation when the button is clicked.
        private void myButton_Clicked(object sender, RoutedEventArgs e)
        {

            // Create a DoubleAnimation to animate the
            // ScaleTransform.
            DoubleAnimation myAnimation =
                new DoubleAnimation(
                    1, // "From" value
                    5, // "To" value
                    new Duration(TimeSpan.FromSeconds(5))
                );
            myAnimation.AutoReverse = true;

            // Create a clock the for the animation.
            AnimationClock myClock = myAnimation.CreateClock();

            // Associate the clock the ScaleX and
            // ScaleY properties of the button's
            // ScaleTransform.
            myScaleTransform.ApplyAnimationClock(
                ScaleTransform.ScaleXProperty, myClock);
            myScaleTransform.ApplyAnimationClock(
                ScaleTransform.ScaleYProperty, myClock);
        }
    }
}
'
'    This example shows how to create and apply
'    an AnimationClock.
'


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


Namespace Microsoft.Samples.Animation.TimingBehaviors
    Public Class AnimationClockExample
        Inherits Page

        Private ReadOnly myScaleTransform As ScaleTransform

        Public Sub New()

            WindowTitle = "Opacity Animation Example"
            Background = Brushes.White
            Dim myStackPanel As New StackPanel With {
                .Margin = New Thickness(20)
            }

                ' Create a button that with a ScaleTransform.
                ' The ScaleTransform will animate when the
                ' button is clicked.
            Dim myButton As New Button With {
                .Margin = New Thickness(50),
                .HorizontalAlignment = HorizontalAlignment.Left,
                .Content = "Click Me"
            }
            myScaleTransform = New ScaleTransform(1,1)
            myButton.RenderTransform = myScaleTransform


            ' Associate an event handler with the
            ' button's Click event.
            AddHandler myButton.Click, AddressOf myButton_Clicked

            myStackPanel.Children.Add(myButton)
            Content = myStackPanel
        End Sub

        ' Create and apply and animation when the button is clicked.
        Private Sub myButton_Clicked(sender As Object, e As RoutedEventArgs)

            ' Create a DoubleAnimation to animate the
            ' ScaleTransform.
            Dim myAnimation As New DoubleAnimation(1, 5, New Duration(TimeSpan.FromSeconds(5))) With {
                .AutoReverse = True
            } ' "To" value -  "From" value

            ' Create a clock the for the animation.
            Dim myClock As AnimationClock = myAnimation.CreateClock()

            ' Associate the clock the ScaleX and
            ' ScaleY properties of the button's
            ' ScaleTransform.
            myScaleTransform.ApplyAnimationClock(ScaleTransform.ScaleXProperty, myClock)
            myScaleTransform.ApplyAnimationClock(ScaleTransform.ScaleYProperty, myClock)
        End Sub
    End Class
End Namespace

Para criar uma árvore de tempo e usá-la para animar propriedades, conclua as etapas a seguir.

  1. Use ParallelTimeline e AnimationTimeline objetos para criar a árvore de temporização.

  2. Use o CreateClock da raiz ParallelTimeline para criar um ClockGrouparquivo .

  3. Itere através Children do e ClockGroup aplique seus objetos filho Clock . Para cada AnimationClock filho, use o ApplyAnimationClock método do objeto que você deseja animar para aplicar o AnimationClock à propriedade especificada

Para obter mais informações sobre objetos de Relógio, consulte o Visão geral da animação e do sistema de tempo.

Animação por quadro: ignorar o sistema de animação e tempo

Use essa abordagem quando precisar ignorar completamente o sistema de animação WPF. Um cenário para essa abordagem são as animações de física, em que cada etapa da animação requer que os objetos sejam recalculados com base no último conjunto de interações de objetos.

Animações por quadro não podem ser definidas dentro de estilos, modelos de controle ou modelos de dados.

Para animar quadro a quadro, registre-se para o Rendering evento do objeto que contém os objetos que deseja animar. Esse método de manipulador de eventos é chamado uma vez por quadro. Cada vez que o WPF marshals os dados de renderização persistentes na árvore visual para a árvore de composição, seu método de manipulador de eventos é chamado.

Em seu manipulador de eventos, realize os cálculos necessários para o efeito da animação e defina as propriedades dos objetos que você deseja animar com esses valores.

Para obter o tempo de apresentação para o quadro atual, o associado a esse evento pode ser convertido como RenderingEventArgs, que fornece uma RenderingTime propriedade que você pode usar para obter o EventArgs tempo de renderização do quadro atual.

Para obter mais informações, consulte a Rendering página.

Confira também