Compartir a través de


Visión general de las animaciones de Desde/Hacia/Por

En este tema se describe cómo usar animaciones From/To/By para animar las propiedades de dependencia. Una animación From/To/By crea una transición entre dos valores.

Prerrequisitos

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

¿Qué es una animación from/to/by?

Una animación From/To/By es un tipo de AnimationTimeline que crea una transición entre un valor inicial y un valor final. La cantidad de tiempo que tarda la transición en completarse viene determinada por la Duration de esa animación.

Puede aplicar una animación From/To/By a una propiedad utilizando un Storyboard en el marcado y en el código, o mediante el método BeginAnimation en el código. También puede usar una animación From/To/By para crear un AnimationClock y aplicarlo a una o varias propiedades. Para obtener más información sobre los diferentes métodos para aplicar animaciones, consulte el Resumen de técnicas de animación de propiedades.

Las animaciones From/To/By no pueden tener más de dos valores de destino. Si necesita una animación que tenga más de dos valores de destino, use una animación de fotograma clave. Las animaciones de fotograma clave se describen en la descripción general de animacionesKey-Frame.

Tipos de animación from/to/by

Dado que las animaciones generan valores de propiedad, hay diferentes tipos de animación para diferentes tipos de propiedad. Para animar una propiedad que toma Double, como la propiedad Width de un elemento, use una animación que produzca valores Double. Para animar una propiedad que requiere un Point, utilice una animación que genere valores Point, y así sucesivamente.

Las clases de animación From/To/By pertenecen al System.Windows.Media.Animation espacio de nombres y usan la siguiente convención de nomenclatura:

<Tipo>Animation

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

WPF proporciona las siguientes clases de animación From/To/By.

Tipo de propiedad Clase de animación correspondiente From/To/By
Byte ByteAnimation
Color ColorAnimation
Decimal DecimalAnimation
Double DoubleAnimation
Int16 Int16Animation
Int32 Int32Animation
Int64 Int64Animation
Point PointAnimation
Quaternion QuaternionAnimation
Rect RectAnimation
Rotation3D Rotation3DAnimation
Single SingleAnimation
Size SizeAnimation
Thickness ThicknessAnimation
Vector3D Vector3DAnimation
Vector VectorAnimation

Valores objetivo

Una animación From/To/By crea una transición entre dos valores de destino. Es habitual especificar un valor inicial (establézcalo mediante la From propiedad ) y un valor final (establézcalo mediante la To propiedad ). Sin embargo, también puede especificar solo un valor inicial, un valor de destino o un valor de desplazamiento. En estos casos, la animación obtiene el valor de destino que falta de la propiedad que se está animando. En la lista siguiente se describen las distintas maneras de especificar los valores de destino de una animación.

  • Valor inicial

    Utilice la From propiedad cuando desee especificar explícitamente el valor inicial de una animación. Puede usar la propiedad From por sí sola, o con la propiedad To o By. Si especifica solo la From propiedad , la animación pasa de ese valor al valor base de la propiedad animada.

  • Valor final

    Para especificar un valor final de una animación, use su To propiedad . Si usa la To propiedad por sí misma, la animación obtiene su valor inicial de la propiedad que se está animando o de la salida de otra animación que se aplica a la misma propiedad. Puede usar la To propiedad junto con la From propiedad para especificar explícitamente los valores iniciales y finales de la animación.

  • Valor de desplazamiento

    La By propiedad permite especificar un desplazamiento en lugar de un valor inicial o final explícito para la animación. La By propiedad de una animación especifica cuánto cambia la animación un valor durante su duración. Puede usar la By propiedad por sí misma o con la From propiedad . Si especifica solo la propiedad By, la animación agrega el valor de desplazamiento al valor base de la propiedad o a la salida de otra animación.

Uso De Valores From/To/By

En las secciones siguientes se describe cómo usar las Frompropiedades , Toy By juntas o por separado.

Los ejemplos de esta sección utilizan un DoubleAnimation, que es un tipo de animación From/To/By, para animar la propiedad Width de un Rectangle que tiene 10 píxeles independientes del dispositivo de alto y 100 píxeles independientes del dispositivo de ancho.

Aunque cada ejemplo usa una DoubleAnimation, las propiedades From, To y By de todas las animaciones From/To/By se comportan de forma idéntica. Aunque cada uno de estos ejemplos usa un Storyboard, puede usar animaciones From/To/By de otras maneras. Para obtener más información, vea Información general sobre técnicas de animación de propiedades.

De/A

Al establecer los valores From y To juntos, la animación avanza del valor especificado por la propiedad From, al valor especificado por la propiedad To.

En el ejemplo siguiente se establece la propiedad From del DoubleAnimation a 50 y su propiedad To a 300. Como resultado, el Width de Rectangle se anima desde 50 a 300.

// Demonstrates the From and To properties used together.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "fromToAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Black;

// Demonstrates the From and To properties used together.
// Animates the rectangle's Width property from 50 to 300 over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.To = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "fromToAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the From and To properties used together.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("fromToAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Black

' Demonstrates the From and To properties used together.
' Animates the rectangle's Width property from 50 to 300 over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.To = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "fromToAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

En

Cuando se establece solo la To propiedad , la animación avanza desde el valor base de la propiedad animada, o desde la salida de una animación de composición que se aplicó anteriormente a la misma propiedad, al valor especificado por la To propiedad .

("Animación de composición" hace referencia a una animación Active o Filling que se aplicó anteriormente a la misma propiedad y que sigue vigente cuando se aplica la animación actual mediante el comportamiento de transferencia Compose).

En el ejemplo siguiente se establece solo la To propiedad de DoubleAnimation a 300. Dado que no se especificó ningún valor inicial, usa DoubleAnimation el valor base (100) de la Width propiedad como su valor inicial. Width de Rectangle se anima desde 100 hasta llegar al valor objetivo de la animación, que es 300.

// Demonstrates the use of the To property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "toAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Gray;

// Demonstrates the To property used by itself. Animates
// the Rectangle's Width property from its base value
// (100) to 300 over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.To = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "toAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the To property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("toAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Gray

' Demonstrates the To property used by itself. Animates
' the Rectangle's Width property from its base value
' (100) to 300 over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.To = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "toAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

Por

Cuando se establece solo la propiedad By de una animación, esta progresa desde el valor base de la propiedad que se está animando, o desde la salida de una animación compuesta hasta la suma de ese valor con el valor especificado por la propiedad By.

En el ejemplo siguiente se establece solo la By propiedad de DoubleAnimation a 300. Dado que el ejemplo no especifica un valor inicial, usa DoubleAnimation el valor base de la Width propiedad, 100, como su valor inicial. El valor final se determina agregando el By valor de la animación, 300, a su valor inicial, 100: 400. Como resultado, el Width de Rectangle se mueve de 100 a 400.

// Demonstrates the use of the By property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "byAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.RoyalBlue;

// Demonstrates the By property used by itself.
// Increments the Rectangle's Width property by 300 over 10 seconds.
// As a result, the Width property is animated from its base value
// (100) to 400 (100 + 300) over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.By = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the By property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("byAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.RoyalBlue

' Demonstrates the By property used by itself.
' Increments the Rectangle's Width property by 300 over 10 seconds.
' As a result, the Width property is animated from its base value
' (100) to 400 (100 + 300) over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.By = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

De Por

Cuando se establecen las propiedades From y By de una animación, la animación progresa desde el valor especificado por la propiedad From al valor especificado por la suma de las propiedades From y By.

En el ejemplo siguiente se establece la propiedad From del DoubleAnimation a 50 y su propiedad By a 300. El valor final se determina agregando el By valor de la animación, 300, a su valor inicial, 50: 350. Como resultado, el Width de Rectangle se anima gráficamente de 50 a 350.

// Demonstrates the use of the From and By properties.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "byAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.BlueViolet;

// Demonstrates the From and By properties used together.
// Increments the Rectangle's Width property by 300 over 10 seconds.
// As a result, the Width property is animated from 50
// to 350 (50 + 300) over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.By = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the From and By properties.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("byAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.BlueViolet

' Demonstrates the From and By properties used together.
' Increments the Rectangle's Width property by 300 over 10 seconds.
' As a result, the Width property is animated from 50
' to 350 (50 + 300) over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.By = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

Desde

Cuando solo se especifica el valor de From de una animación, la animación avanza desde el valor que especifica la propiedad From, hasta el valor base de la propiedad que se está animando o hasta el resultado de una animación de composición.

En el ejemplo siguiente se establece solo la propiedad From del DoubleAnimation a 50. Dado que no se especificó ningún valor final, usa DoubleAnimation el valor base de la Width propiedad , 100, como su valor final. Width de Rectangle se anima desde 50 hasta el valor base de la propiedad Width, 100.

// Demonstrates the use of the From property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "fromAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Purple;

// Demonstrates the From property used by itself. Animates the
// rectangle's Width property from 50 to its base value (100)
// over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "fromAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the From property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("fromAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Purple

' Demonstrates the From property used by itself. Animates the
' rectangle's Width property from 50 to its base value (100)
' over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "fromAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

A/Por

Si establece tanto las propiedades To como By de una animación, se omite la propiedad By.

Otros tipos de animación

Las animaciones From/To/By no son el único tipo de animaciones que proporciona WPF; también ofrece animaciones de fotogramas clave y animaciones basadas en trayectorias.

WPF también le permite crear sus propios tipos de animación personalizados. Para obtener más información, vea Información general sobre animaciones personalizadas.

Consulte también