方法: キー フレームを使用して Double 値をアニメーション化する

この例では、Double を受け取るプロパティの値をキー フレームを使用してアニメーション化する方法を示します。

次の例では、画面を横切るように四角形を移動します。 この例では、DoubleAnimationUsingKeyFrames クラスを使用して、Rectangle に適用された TranslateTransformX プロパティをアニメーション化します。 無期限に繰り返すこのアニメーションでは、次の方法で 3 つのキー フレームを使用します。

  1. 最初の 3 秒間は、LinearDoubleKeyFrame クラスのインスタンスを使用して、四角形を開始位置からパスに沿って 500 の位置まで一定の速度で移動します。 LinearDoubleKeyFrame のような線形キー フレームは、ある値から次の値への滑らかで直線的な遷移を作成します。

  2. 4 秒目の後わりに、DiscreteDoubleKeyFrame クラスのインスタンスを使用して、四角形を次の位置まで突然移動します。 DiscreteDoubleKeyFrame のような不連続キー フレームは、ある値から次の値への突然の変化を作成します。 この例では、開始位置にあった四角形が突然 500 の位置に出現します。

  3. 最後の 2 秒間は、SplineDoubleKeyFrame クラスのインスタンスを使用して、四角形を開始位置まで戻します。 SplineDoubleKeyFrame のようなスプライン キー フレームは、KeySpline プロパティの値に従って、ある値から次の値への可変遷移を作成します。 この例では、四角形の動きは最初はゆっくりしていますが、時間セグメントの終点に向かった急激に速くなります。

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

namespace Microsoft.Samples.KeyFrameExamples
{
    /// <summary>
    /// This example shows how to use the DoubleAnimationUsingKeyFrames class to
    /// animate the position of an object.
    /// Key frame animations enable you to create complex animations
    /// by specifying multiple destination values
    /// and controlling the animation's interpolation method.
    /// </summary>
    public class AltDoubleAnimationUsingKeyFramesExample : Page
    {
        public AltDoubleAnimationUsingKeyFramesExample()
        {
            Title = "DoubleAnimationUsingKeyFrames Example";
            Background = Brushes.White;
            Margin = new Thickness(20);

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

            // Create a rectangle.
            Rectangle aRectangle = new Rectangle();
            aRectangle.Width = 100;
            aRectangle.Height = 100;
            aRectangle.Stroke = Brushes.Black;
            aRectangle.StrokeThickness = 5;

            // Create a Canvas to contain and
            // position the rectangle.
            Canvas containerCanvas = new Canvas();
            containerCanvas.Width = 610;
            containerCanvas.Height = 300;
            containerCanvas.Children.Add(aRectangle);
            Canvas.SetTop(aRectangle, 100);
            Canvas.SetLeft(aRectangle, 10);

            // Create a TranslateTransform to
            // move the rectangle.
            TranslateTransform animatedTranslateTransform =
                new TranslateTransform();
            aRectangle.RenderTransform = animatedTranslateTransform;

            // Assign the TranslateTransform a name so that
            // it can be targeted by a Storyboard.
            this.RegisterName(
                "AnimatedTranslateTransform", animatedTranslateTransform);

            // Create a DoubleAnimationUsingKeyFrames to
            // animate the TranslateTransform.
            DoubleAnimationUsingKeyFrames translationAnimation
                = new DoubleAnimationUsingKeyFrames();
            translationAnimation.Duration = TimeSpan.FromSeconds(6);

            // Animate from the starting position to 500
            // over the first second using linear
            // interpolation.
            translationAnimation.KeyFrames.Add(
                new LinearDoubleKeyFrame(
                    500, // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3))) // KeyTime
                );

            // Animate from 500 (the value of the previous key frame)
            // to 400 at 4 seconds using discrete interpolation.
            // Because the interpolation is discrete, the rectangle will appear
            // to "jump" from 500 to 400.
            translationAnimation.KeyFrames.Add(
                new DiscreteDoubleKeyFrame(
                    400, // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4))) // KeyTime
                );

            // Animate from 400 (the value of the previous key frame) to 0
            // over two seconds, starting at 4 seconds (the key time of the
            // last key frame) and ending at 6 seconds.
            translationAnimation.KeyFrames.Add(
                new SplineDoubleKeyFrame(
                    0, // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(6)), // KeyTime
                    new KeySpline(0.6,0.0,0.9,0.0) // KeySpline
                    )
                );

            // Set the animation to repeat forever.
            translationAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Set the animation to target the X property
            // of the object named "AnimatedTranslateTransform."
            Storyboard.SetTargetName(translationAnimation, "AnimatedTranslateTransform");
            Storyboard.SetTargetProperty(
                translationAnimation, new PropertyPath(TranslateTransform.XProperty));

            // Create a storyboard to apply the animation.
            Storyboard translationStoryboard = new Storyboard();
            translationStoryboard.Children.Add(translationAnimation);

            // Start the storyboard after the rectangle loads.
            aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
            {
                translationStoryboard.Begin(this);
            };

            Content = containerCanvas;
        }
    }
}

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

Namespace Microsoft.Samples.KeyFrameExamples
    ''' <summary>
    ''' This example shows how to use the DoubleAnimationUsingKeyFrames class to
    ''' animate the position of an object.
    ''' Key frame animations enable you to create complex animations 
    ''' by specifying multiple destination values
    ''' and controlling the animation's interpolation method.
    ''' </summary>
    Public Class AltDoubleAnimationUsingKeyFramesExample
        Inherits Page
        Public Sub New()
            Title = "DoubleAnimationUsingKeyFrames Example"
            Background = Brushes.White
            Margin = New Thickness(20)

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

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

            ' Create a Canvas to contain and
            ' position the rectangle.
            Dim containerCanvas As New Canvas()
            containerCanvas.Width = 610
            containerCanvas.Height = 300
            containerCanvas.Children.Add(aRectangle)
            Canvas.SetTop(aRectangle, 100)
            Canvas.SetLeft(aRectangle, 10)

            ' Create a TranslateTransform to 
            ' move the rectangle.
            Dim animatedTranslateTransform As New TranslateTransform()
            aRectangle.RenderTransform = animatedTranslateTransform

            ' Assign the TranslateTransform a name so that
            ' it can be targeted by a Storyboard.
            Me.RegisterName("AnimatedTranslateTransform", animatedTranslateTransform)

            ' Create a DoubleAnimationUsingKeyFrames to
            ' animate the TranslateTransform.
            Dim translationAnimation As New DoubleAnimationUsingKeyFrames()
            translationAnimation.Duration = TimeSpan.FromSeconds(6)

            ' Animate from the starting position to 500
            ' over the first second using linear
            ' interpolation.
            translationAnimation.KeyFrames.Add(New LinearDoubleKeyFrame(500, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3)))) ' KeyTime -  Target value (KeyValue)

            ' Animate from 500 (the value of the previous key frame) 
            ' to 400 at 4 seconds using discrete interpolation.
            ' Because the interpolation is discrete, the rectangle will appear
            ' to "jump" from 500 to 400.
            translationAnimation.KeyFrames.Add(New DiscreteDoubleKeyFrame(400, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4)))) ' KeyTime -  Target value (KeyValue)

            ' Animate from 400 (the value of the previous key frame) to 0
            ' over two seconds, starting at 4 seconds (the key time of the
            ' last key frame) and ending at 6 seconds.
            translationAnimation.KeyFrames.Add(New SplineDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(6)), New KeySpline(0.6,0.0,0.9,0.0))) ' KeySpline -  KeyTime -  Target value (KeyValue)

            ' Set the animation to repeat forever. 
            translationAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Set the animation to target the X property
            ' of the object named "AnimatedTranslateTransform."
            Storyboard.SetTargetName(translationAnimation, "AnimatedTranslateTransform")
            Storyboard.SetTargetProperty(translationAnimation, New PropertyPath(TranslateTransform.XProperty))

            ' Create a storyboard to apply the animation.
            Dim translationStoryboard As New Storyboard()
            translationStoryboard.Children.Add(translationAnimation)

            ' Start the storyboard after the rectangle loads.
            AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) translationStoryboard.Begin(Me)

            Content = containerCanvas
        End Sub

    End Class
End Namespace
<!-- This example shows how to use the DoubleAnimationUsingKeyFrames to 
     animate the position of an object. 
     Key frame animations enable you to create complex animations 
     by specifying multiple destination values
     and controlling the animation's interpolation method.
-->
<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="DoubleAnimationUsingKeyFrames Example"
  Background="White" Margin="20">       
  <Canvas Width="610" Height="300">
  
    <!-- The position of this rectangle is animated using 
         a key frame animation. -->
    <Rectangle 
      Canvas.Top="100"
      Canvas.Left="10"
      Height="100"
      Width="100"
      Stroke="Black"
      StrokeThickness="5">
      <Rectangle.RenderTransform>
        <TranslateTransform x:Name="AnimatedTranslateTransform" />
      </Rectangle.RenderTransform>
      
      <Rectangle.Triggers>
        <EventTrigger RoutedEvent="Rectangle.Loaded">
          <BeginStoryboard>
            <Storyboard>

              <!-- Animate the TranslateTransform.X property using 3 KeyFrames
                   which animates the rectangle along a straight line. 
                   This animation repeats indefinitely. -->
              <DoubleAnimationUsingKeyFrames
                Storyboard.TargetName="AnimatedTranslateTransform"
                Storyboard.TargetProperty="X"
                Duration="0:0:6"
                RepeatBehavior="Forever">

                <!-- Using a LinearDoubleKeyFrame, the rectangle moves 
                     steadily from its starting position to 500 over 
                     the first 3 seconds.  -->
                <LinearDoubleKeyFrame Value="500" KeyTime="0:0:3" />

                <!-- Using a DiscreteDoubleKeyFrame, the rectangle suddenly 
                     appears at 400 after the fourth second of the animation. -->
                <DiscreteDoubleKeyFrame Value="400" KeyTime="0:0:4" />

                <!-- Using a SplineDoubleKeyFrame, the rectangle moves 
                     back to its starting point. The
                     animation starts out slowly at first and then speeds up. 
                     This KeyFrame ends after the 6th
                     second. -->
                <SplineDoubleKeyFrame KeySpline="0.6,0.0 0.9,0.00" Value="0" KeyTime="0:0:6" />
              </DoubleAnimationUsingKeyFrames>
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Rectangle.Triggers>
    </Rectangle>
  </Canvas>
</Page>

サンプル全体については、「キーフレーム アニメーションのサンプル」を参照してください。

他のアニメーション例との一貫性を保つために、この例のコード バージョンでは、Storyboard オブジェクトを使用して DoubleAnimationUsingKeyFrames を適用しています。 ただし、コード内で 1 つのアニメーションを適用する場合は、Storyboard よりも BeginAnimation メソッドを使用する方が簡単です。 例については、「ストーリーボードを使用せずにプロパティをアニメーション化する」を参照してください。

関連項目