Cómo: Controlar la temporización de animaciones y fotogramas clave

En este ejemplo se muestra cómo controlar el tiempo de los fotogramas clave dentro de una animación de fotograma clave. Como otras animaciones, las animaciones de fotogramas clave tienen una propiedad Duration. Además de especificar la duración de una animación, debe especificar qué parte de esa duración se asigna a cada uno de sus fotogramas clave. Para asignar el tiempo, especifique una estructura KeyTime para cada fotograma clave de la animación.

La estructura KeyTime para cada fotograma clave especifica cuándo finaliza un fotograma clave (no especifica el período de tiempo que se reproduce un fotograma clave). Puede especificar KeyTime como un valor TimeSpan, como un porcentaje o como los valores especiales Uniform o Paced.

Ejemplo

En el ejemplo siguiente se usa DoubleAnimationUsingKeyFrames para animar un rectángulo a través de la pantalla. Los tiempos clave de los fotogramas clave se establecen con valores TimeSpan.

/*
   This Rectangle is animated with KeyTimes using TimeSpan Values.
   It moves horizontally to 100 in the first 3 seconds, 100 to 300 in
   the next second, and 300 to 500 in the last 6 seconds.
*/

// Create the a rectangle.
Rectangle aRectangle = new Rectangle();
aRectangle.Fill = Brushes.Blue;
aRectangle.Stroke = Brushes.Black;
aRectangle.StrokeThickness = 5;
aRectangle.Width = 50;
aRectangle.Height = 50;

// Create a transform to move the rectangle
// across the screen.
TranslateTransform translateTransform1 =
    new TranslateTransform();
aRectangle.RenderTransform = translateTransform1;

// Create a DoubleAnimationUsingKeyFrames
// to animate the transform.
DoubleAnimationUsingKeyFrames transformAnimation =
    new DoubleAnimationUsingKeyFrames();
transformAnimation.Duration = TimeSpan.FromSeconds(10);

// Animate to 100 at 3 seconds.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(100, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))));

// Animate to 300 at 4 seconds.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(300, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4))));

// Animate to 500 at 10 seconds.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(500, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(10))));

// Start the animation when the rectangle is loaded.
aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
{
    translateTransform1.BeginAnimation(TranslateTransform.XProperty, transformAnimation);
};

'            
'               This Rectangle is animated with KeyTimes using TimeSpan Values. 
'               It moves horizontally to 100 in the first 3 seconds, 100 to 300 in 
'               the next second, and 300 to 500 in the last 6 seconds.
'            

            ' Create the a rectangle.
            Dim aRectangle As New Rectangle()
            aRectangle.Fill = Brushes.Blue
            aRectangle.Stroke = Brushes.Black
            aRectangle.StrokeThickness = 5
            aRectangle.Width = 50
            aRectangle.Height = 50

            ' Create a transform to move the rectangle
            ' across the screen.
            Dim translateTransform1 As New TranslateTransform()
            aRectangle.RenderTransform = translateTransform1

            ' Create a DoubleAnimationUsingKeyFrames
            ' to animate the transform.
            Dim transformAnimation As New DoubleAnimationUsingKeyFrames()
            transformAnimation.Duration = TimeSpan.FromSeconds(10)

            ' Animate to 100 at 3 seconds.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(100, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))))

            ' Animate to 300 at 4 seconds.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(300, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4))))

            ' Animate to 500 at 10 seconds.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(500, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(10))))

            ' Start the animation when the rectangle is loaded.
            AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) translateTransform1.BeginAnimation(TranslateTransform.XProperty, transformAnimation)

<!-- This Rectangle is animated with KeyTimes using TimeSpan Values. 
     It moves horizontally to 100 in the first 3 seconds, 100 to 300 in 
     the next second, and 300 to 500 in the last 6 seconds. -->
<Rectangle Fill="Blue" Stroke="Black" StrokeThickness="5"
  Width="50" Height="50">
  <Rectangle.RenderTransform>
    <TranslateTransform x:Name="TranslateTransform1" />
  </Rectangle.RenderTransform>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetName="TranslateTransform1" 
            Storyboard.TargetProperty="X"
            Duration="0:0:10">

            <!-- These KeyTime properties are specified as TimeSpan values 
                 which are in the form of "hours:minutes:seconds". -->
            <LinearDoubleKeyFrame Value="100" KeyTime="0:0:3" />
            <LinearDoubleKeyFrame Value="300" KeyTime="0:0:4" />
            <LinearDoubleKeyFrame Value="500" KeyTime="0:0:10" />
          </DoubleAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

En la ilustración siguiente se muestra cuándo se alcanza el valor de cada fotograma clave.

Captura de pantalla en la que se muestran cuatro fotogramas clave con un color de degradado azul creciente que tiene los valores de 0, 3, 4 y 10 segundos.

En el ejemplo siguiente se muestra una animación idéntica, salvo que los tiempos clave de los fotogramas clave se establecen con valores de porcentaje.

/*
  This rectangle moves horizontally to 100 in the first 3 seconds,
  100 to 300 in  the next second, and 300 to 500 in the last 6 seconds.
*/

// Create the a rectangle.
Rectangle aRectangle = new Rectangle();
aRectangle.Fill = Brushes.Purple;
aRectangle.Stroke = Brushes.Black;
aRectangle.StrokeThickness = 5;
aRectangle.Width = 50;
aRectangle.Height = 50;

// Create a transform to move the rectangle
// across the screen.
TranslateTransform translateTransform2 =
    new TranslateTransform();
aRectangle.RenderTransform = translateTransform2;

// Create a DoubleAnimationUsingKeyFrames
// to animate the transform.
DoubleAnimationUsingKeyFrames transformAnimation =
    new DoubleAnimationUsingKeyFrames();
transformAnimation.Duration = TimeSpan.FromSeconds(10);

// Animate to 100 at 30% of the animation's duration.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(100, KeyTime.FromPercent(0.3)));

// Animate to 300 at 40% of the animation's duration.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(300, KeyTime.FromPercent(0.4)));

// Animate to 500 at 100% of the animation's duration.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(500, KeyTime.FromPercent(1.0)));

// Start the animation when the rectangle is loaded.
aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
{
    translateTransform2.BeginAnimation(TranslateTransform.XProperty, transformAnimation);
};
'            
'              This rectangle moves horizontally to 100 in the first 3 seconds, 
'              100 to 300 in  the next second, and 300 to 500 in the last 6 seconds.
'            

            ' Create the a rectangle.
            Dim aRectangle As New Rectangle()
            aRectangle.Fill = Brushes.Purple
            aRectangle.Stroke = Brushes.Black
            aRectangle.StrokeThickness = 5
            aRectangle.Width = 50
            aRectangle.Height = 50

            ' Create a transform to move the rectangle
            ' across the screen.
            Dim translateTransform2 As New TranslateTransform()
            aRectangle.RenderTransform = translateTransform2

            ' Create a DoubleAnimationUsingKeyFrames
            ' to animate the transform.
            Dim transformAnimation As New DoubleAnimationUsingKeyFrames()
            transformAnimation.Duration = TimeSpan.FromSeconds(10)

            ' Animate to 100 at 30% of the animation's duration.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(100, KeyTime.FromPercent(0.3)))

            ' Animate to 300 at 40% of the animation's duration.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(300, KeyTime.FromPercent(0.4)))

            ' Animate to 500 at 100% of the animation's duration.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(500, KeyTime.FromPercent(1.0)))

            ' Start the animation when the rectangle is loaded.
            AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) translateTransform2.BeginAnimation(TranslateTransform.XProperty, transformAnimation)
<!-- This rectangle moves horizontally to 100 in the first 3 seconds, 
     100 to 300 in  the next second, and 300 to 500 in the last 6 seconds.-->
<Rectangle Fill="Purple" Stroke="Black" StrokeThickness="5"
  Width="50" Height="50">
  <Rectangle.RenderTransform>
    <TranslateTransform x:Name="TranslateTransform2" />
  </Rectangle.RenderTransform>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetName="TranslateTransform2" 
            Storyboard.TargetProperty="X"
            Duration="0:0:10">

            <!-- KeyTime properties are expressed as Percentages. -->
            <LinearDoubleKeyFrame Value="100" KeyTime="30%" />
            <LinearDoubleKeyFrame Value="300" KeyTime="40%" />
            <LinearDoubleKeyFrame Value="500" KeyTime="100%" />
          </DoubleAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

En la ilustración siguiente se muestra cuándo se alcanza el valor de cada fotograma clave.

Captura de pantalla en la que se muestran cuatro fotogramas clave con un color de degradado púrpura creciente que tiene los valores de 0, 3, 4 y 10 segundos.

En el ejemplo siguiente se usan valores de tiempo clave Uniform.

/*
   This rectangle is animated with KeyTimes using Uniform values.
   Goes to 100 in the first 3.3 seconds, 100 to
   300 in the next 3.3 seconds, 300 to 500 in the last 3.3 seconds.
*/

// Create the a rectangle.
Rectangle aRectangle = new Rectangle();
aRectangle.Fill = Brushes.Red;
aRectangle.Stroke = Brushes.Black;
aRectangle.StrokeThickness = 5;
aRectangle.Width = 50;
aRectangle.Height = 50;

// Create a transform to move the rectangle
// across the screen.
TranslateTransform translateTransform3 =
    new TranslateTransform();
aRectangle.RenderTransform = translateTransform3;

// Create a DoubleAnimationUsingKeyFrames
// to animate the transform.
DoubleAnimationUsingKeyFrames transformAnimation =
    new DoubleAnimationUsingKeyFrames();
transformAnimation.Duration = TimeSpan.FromSeconds(10);

/*
   KeyTime properties are expressed with values of Uniform. When a key time is set to
   "Uniform" the total allotted time of the animation is divided evenly between key frames.
   In this example, the total duration of the animation is ten seconds and there are four
   key frames each of which are set to "Uniform", therefore, the duration of each key frame
   is 3.3 seconds (10/3).
 */

// Animate to 100.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(100, KeyTime.Uniform));

// Animate to 300.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(300, KeyTime.Uniform));

// Animate to 500.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(500, KeyTime.Uniform));

// Start the animation when the rectangle is loaded.
aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
{
    translateTransform3.BeginAnimation(TranslateTransform.XProperty, transformAnimation);
};

'            
'               This rectangle is animated with KeyTimes using Uniform values. 
'               Goes to 100 in the first 3.3 seconds, 100 to
'               300 in the next 3.3 seconds, 300 to 500 in the last 3.3 seconds.
'            

            ' Create the a rectangle.
            Dim aRectangle As New Rectangle()
            aRectangle.Fill = Brushes.Red
            aRectangle.Stroke = Brushes.Black
            aRectangle.StrokeThickness = 5
            aRectangle.Width = 50
            aRectangle.Height = 50

            ' Create a transform to move the rectangle
            ' across the screen.
            Dim translateTransform3 As New TranslateTransform()
            aRectangle.RenderTransform = translateTransform3

            ' Create a DoubleAnimationUsingKeyFrames
            ' to animate the transform.
            Dim transformAnimation As New DoubleAnimationUsingKeyFrames()
            transformAnimation.Duration = TimeSpan.FromSeconds(10)

'            
'               KeyTime properties are expressed with values of Uniform. When a key time is set to
'               "Uniform" the total allotted time of the animation is divided evenly between key frames.  
'               In this example, the total duration of the animation is ten seconds and there are four 
'               key frames each of which are set to "Uniform", therefore, the duration of each key frame 
'               is 3.3 seconds (10/3).
'             

            ' Animate to 100.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(100, KeyTime.Uniform))

            ' Animate to 300.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(300, KeyTime.Uniform))

            ' Animate to 500.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(500, KeyTime.Uniform))

            ' Start the animation when the rectangle is loaded.
            AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) translateTransform3.BeginAnimation(TranslateTransform.XProperty, transformAnimation)

<!-- This rectangle is animated with KeyTimes using Uniform values. 
     Goes to 100 in the first 3.3 seconds, 100 to
     300 in the next 3.3 seconds, 300 to 500 in the last 3.3 seconds. -->
<Rectangle Fill="Red" Stroke="Black" StrokeThickness="5"
  Width="50" Height="50">
  <Rectangle.RenderTransform>
    <TranslateTransform x:Name="TranslateTransform3" />
  </Rectangle.RenderTransform>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetName="TranslateTransform3" 
            Storyboard.TargetProperty="X"
            Duration="0:0:10">

            <!--   KeyTime properties are expressed with values of Uniform. When a key time is set to
                   "Uniform" the total allotted time of the animation is divided evenly between key frames.  
                   In this example, the total duration of the animation is ten seconds and there are four 
                   key frames each of which are set to "Uniform", therefore, the duration of each key frame 
                   is 3.3 seconds (10/3). -->
            <LinearDoubleKeyFrame Value="100" KeyTime="Uniform" />
            <LinearDoubleKeyFrame Value="300" KeyTime="Uniform" />
            <LinearDoubleKeyFrame Value="500" KeyTime="Uniform" />
          </DoubleAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

En la ilustración siguiente se muestra cuándo se alcanza el valor de cada fotograma clave.

Los valores de clave se alcanzan en 3,3; 6,6 y 9,9 segundos.

En el ejemplo final se usan valores de tiempo clave Paced.

/*
   This rectangle is animated with KeyTimes using Paced Values.
   The rectangle moves between key frames at uniform rate except for first key frame
   because using a Paced value on the first KeyFrame in a collection of frames gives a time of zero.
*/

// Create the a rectangle.
Rectangle aRectangle = new Rectangle();
aRectangle.Fill = Brushes.Orange;
aRectangle.Stroke = Brushes.Black;
aRectangle.StrokeThickness = 5;
aRectangle.Width = 50;
aRectangle.Height = 50;

// Create a transform to move the rectangle
// across the screen.
TranslateTransform translateTransform4 =
    new TranslateTransform();
aRectangle.RenderTransform = translateTransform4;

// Create a DoubleAnimationUsingKeyFrames
// to animate the transform.
DoubleAnimationUsingKeyFrames transformAnimation =
    new DoubleAnimationUsingKeyFrames();
transformAnimation.Duration = TimeSpan.FromSeconds(10);

/*
   Use Paced values when a constant rate is desired.
   The time allocated to a key frame with a KeyTime of "Paced" is
   determined by the time allocated to the other key frames of the animation. This time is
   calculated to attempt to give a "paced" or "constant velocity" for the animation.
 */

// Animate to 100.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(100, KeyTime.Paced));

// Animate to 300.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(300, KeyTime.Paced));

// Animate to 500.
transformAnimation.KeyFrames.Add(
    new LinearDoubleKeyFrame(500, KeyTime.Paced));

// Start the animation when the rectangle is loaded.
aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
{
    translateTransform4.BeginAnimation(TranslateTransform.XProperty, transformAnimation);
};

'            
'               This rectangle is animated with KeyTimes using Paced Values. 
'               The rectangle moves between key frames at uniform rate except for first key frame
'               because using a Paced value on the first KeyFrame in a collection of frames gives a time of zero.
'            

            ' Create the a rectangle.
            Dim aRectangle As New Rectangle()
            aRectangle.Fill = Brushes.Orange
            aRectangle.Stroke = Brushes.Black
            aRectangle.StrokeThickness = 5
            aRectangle.Width = 50
            aRectangle.Height = 50

            ' Create a transform to move the rectangle
            ' across the screen.
            Dim translateTransform4 As New TranslateTransform()
            aRectangle.RenderTransform = translateTransform4

            ' Create a DoubleAnimationUsingKeyFrames
            ' to animate the transform.
            Dim transformAnimation As New DoubleAnimationUsingKeyFrames()
            transformAnimation.Duration = TimeSpan.FromSeconds(10)

'            
'               Use Paced values when a constant rate is desired. 
'               The time allocated to a key frame with a KeyTime of "Paced" is
'               determined by the time allocated to the other key frames of the animation. This time is 
'               calculated to attempt to give a "paced" or "constant velocity" for the animation.
'             

            ' Animate to 100.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(100, KeyTime.Paced))

            ' Animate to 300.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(300, KeyTime.Paced))

            ' Animate to 500.
            transformAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(500, KeyTime.Paced))

            ' Start the animation when the rectangle is loaded.
            AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) translateTransform4.BeginAnimation(TranslateTransform.XProperty, transformAnimation)

<!-- This rectangle is animated with KeyTimes using Paced Values. 
     The rectangle moves between key frames at uniform rate except for first key frame
     because using a Paced value on the first KeyFrame in a collection of frames gives a time of zero. -->
<Rectangle Fill="Orange" Stroke="Black" StrokeThickness="5"
  Width="50" Height="50">
  <Rectangle.RenderTransform>
    <TranslateTransform x:Name="TranslateTransform4" />
  </Rectangle.RenderTransform>
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetName="TranslateTransform4" 
            Storyboard.TargetProperty="X"
            Duration="0:0:10">

            <!-- Use Paced values when a constant rate is desired. 
                 The time allocated to a key frame with a KeyTime of "Paced" is
                 determined by the time allocated to the other key frames of the animation. This time is 
                 calculated to attempt to give a "paced" or "constant velocity" for the animation. -->
            <LinearDoubleKeyFrame Value="100" KeyTime="Paced" />
            <LinearDoubleKeyFrame Value="300" KeyTime="Paced" />
            <LinearDoubleKeyFrame Value="500" KeyTime="Paced" />
          </DoubleAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

En la ilustración siguiente se muestra cuándo se alcanza el valor de cada fotograma clave.

Los valores de clave se alcanzan en 0, 5 y 10 segundos.

Por motivos de simplicidad, las versiones de código de este ejemplo usan animaciones locales, no guiones gráficos, porque solo se aplica una única animación a una única propiedad, pero los ejemplos se pueden modificar para usar guiones gráficos en su lugar. Para obtener un ejemplo en el que se muestra cómo declarar un guión gráfico en el código, vea Cómo: Animar una propiedad utilizando un guión gráfico.

Para consultar el ejemplo completo, vea Ejemplo de animación mediante fotogramas clave. Para más información sobre las animaciones de fotogramas clave, consulte Información general sobre animaciones de fotogramas clave.

Vea también