Compartir a través de


Introducción a las técnicas de animación de propiedades

En este tema se describen los distintos enfoques para animar propiedades: guiones gráficos, animaciones locales, relojes y animaciones por fotograma.

Prerrequisitos

Para comprender este tema, debe estar familiarizado con las características básicas de animación descritas en Información general de animación.

Diferentes formas de animar

Dado que hay muchos escenarios diferentes para animar propiedades, WPF proporciona varios enfoques para animar propiedades.

Para cada enfoque, la tabla siguiente indica si se puede usar por instancia, en estilos, en plantillas de control o en plantillas de datos; si se puede usar en XAML; y si el enfoque le permite controlar interactivamente la animación. "Por instancia" hace referencia a la técnica de aplicar una animación o guion gráfico directamente a instancias de un objeto, en lugar de en un estilo, plantilla de control o plantilla de datos.

Técnica de animación Escenarios Admite XAML Controlable de forma interactiva
Animación de guion gráfico Por instancia, Style, , ControlTemplate, DataTemplate
Animación local Por cada instancia No No
Animación del reloj Por cada instancia No
Animación por fotograma Por cada instancia No No disponible

Animaciones de guion gráfico

Usa un Storyboard cuando quieras definir y aplicar tus animaciones en XAML, controla interactivamente las animaciones después de iniciarlas, crea un árbol complejo de animaciones o anima en , StyleControlTemplate o DataTemplate. Para que un Storyboardobjeto se anime mediante , debe ser o FrameworkElementFrameworkContentElement , o debe usarse para establecer un FrameworkElement objeto o FrameworkContentElement. Para obtener más información, consulte Información general sobre guiones gráficos.

Un Storyboard es un tipo especial de contenedor Timeline que proporciona información de destino para las animaciones que contiene. Para animar con , Storyboardcomplete los tres pasos siguientes.

  1. Declare una Storyboard y una o varias animaciones.

  2. Use las TargetName propiedades adjuntas y TargetProperty para especificar el objeto de destino y la propiedad de cada animación.

  3. (Solo código) Defina un NameScope para o FrameworkElementFrameworkContentElement . Registre los nombres de los objetos que se van a animar con ese FrameworkElement o FrameworkContentElement.

  4. Inicie el .Storyboard

Al iniciar Storyboard, las animaciones se aplican a las propiedades que animan y comienzan. Hay dos maneras de comenzar Storyboard: puedes usar el método Begin proporcionado por la clase Storyboard, o bien puedes usar una acción BeginStoryboard. La única manera de animar en XAML es usar una BeginStoryboard acción. Una BeginStoryboard acción se puede usar en una EventTrigger, propiedad Trigger, o en un DataTrigger.

En la siguiente tabla se muestran los diferentes lugares donde se admite cada técnica de inicio: por instancia, por estilo, plantilla de control y plantilla de datos.

Guión gráfico comienza a usar... Por cada instancia Estilo Plantilla de control Plantilla de datos Ejemplo
BeginStoryboard y un EventTrigger Animar una propiedad mediante un guión gráfico
BeginStoryboard y una propiedad Trigger No Desencadenar una animación cuando cambia un valor de propiedad
BeginStoryboard y DataTrigger No Cómo: Desencadenar una animación cuando cambian los datos
método Begin No No No Animar una propiedad mediante un guión gráfico

Para obtener más información sobre Storyboard los objetos, vea Información general sobre guiones gráficos.

Animaciones locales

Las animaciones locales proporcionan una manera cómoda de animar una propiedad de dependencia de cualquier Animatable objeto. Usa animaciones locales cuando quieras aplicar una sola animación a una propiedad y no necesitas controlar interactivamente la animación después de que se inicie. A diferencia de Storyboard una animación, una animación local puede animar un objeto que no está asociado a un FrameworkElement o un FrameworkContentElement. Tampoco tienes que definir un NameScope para este tipo de animación.

Las animaciones locales solo se pueden usar en el código y no se pueden definir en estilos, plantillas de control o plantillas de datos. Una animación local no se puede controlar interactivamente después de iniciarse.

Para animar con una animación local, complete los pasos siguientes.

  1. Cree un objeto AnimationTimeline.

  2. Utilice el BeginAnimation método del objeto que desea animar para aplicar a AnimationTimeline la propiedad que especifique.

En el ejemplo siguiente se muestra cómo animar el ancho y el color de fondo de un Button.

/*

   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

Animaciones de reloj

Use Clock objetos cuando desee animar sin usar Storyboard y desee crear árboles de tiempo complejos o controlar interactivamente las animaciones una vez que comiencen. Puede usar objetos Clock para animar una propiedad de dependencia de cualquier Animatable objeto.

No se pueden usar Clock objetos directamente para animar en estilos, plantillas de control o plantillas de datos. (El sistema de animación y tiempo usa Clock objetos para aplicar animaciones en estilos, plantillas de control y plantillas de datos, pero debe crear esos Clock objetos a partir de un Storyboard. Para obtener más información sobre la relación entre Storyboard objetos y Clock objetos, vea Panorama del sistema de animación y tiempo.)

Para aplicar una única Clock a una propiedad, siga estos pasos.

  1. Cree un objeto AnimationTimeline.

  2. Utilice el método CreateClock de AnimationTimeline para crear un AnimationClock.

  3. Utilice el ApplyAnimationClock método del objeto que desea animar para aplicar a AnimationClock la propiedad que especifique.

En el ejemplo siguiente se muestra cómo crear un AnimationClock objeto y aplicarlo a dos propiedades similares.

/*
    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 crear un árbol de tiempo y utilizarlo para animar las propiedades, complete los siguientes pasos.

  1. Utilice ParallelTimeline y AnimationTimeline objetos para crear el árbol de temporización.

  2. Use el CreateClock de la raíz ParallelTimeline para crear un ClockGroup.

  3. Recorre en iteración el Children objeto de ClockGroup y aplica sus objetos secundarios Clock . Para cada AnimationClock niño, use el método ApplyAnimationClock del objeto que desea animar para aplicar la propiedad que especifique a AnimationClock.

Para obtener más información sobre los objetos Clock, consulte la Visión general del sistema de animación y temporización.

Per-Frame Animación: omitir la Animación y el Sistema de Temporización

Use este enfoque cuando necesite omitir completamente el sistema de animación wpf. Un escenario para este enfoque es animaciones físicas, donde cada paso de la animación requiere que los objetos se vuelvan a calcular en función del último conjunto de interacciones de objetos.

Las animaciones por fotograma no se pueden definir dentro de estilos, plantillas de control ni plantillas de datos.

Para animar fotograma a fotograma, se inscribe en el Rendering evento del objeto contenedor de los objetos que desea animar. Este método de controlador de eventos se llama una vez por fotograma. Cada vez que WPF organiza los datos de representación persistentes del árbol visual hacia el árbol de composición, se llama a su método controlador de eventos.

En el controlador de eventos, realice los cálculos necesarios para el efecto de animación y establezca las propiedades de los objetos que desea animar con estos valores.

Para obtener la hora de presentación del marco actual, el EventArgs asociado a este evento se puede convertir en RenderingEventArgs, que proporciona la propiedad RenderingTime que puede usar para obtener el tiempo de representación del fotograma actual.

Para obtener más información, consulte la Rendering página.

Consulte también