Поделиться через


Практическое руководство. Анимация прямоугольника с помощью ключевых кадров

В этом примере показано, как можно анимировать свойство Rect объекта RectangleGeometry с использованием ключевых кадров.

Пример

В следующем примере используется класс RectAnimationUsingKeyFrames для анимации свойства Rect объекта RectangleGeometry. Эта анимация использует три ключевых кадра следующим образом:

  1. В течение первых двух секунд используется экземпляр класса LinearRectKeyFrame для анимации постепенного изменения положения, ширины и высоты прямоугольника. Линейные ключевые кадры, например LinearRectKeyFrame, создают плавный линейный переход от одного значения к другому.

  2. В конце следующей половины секунды используется экземпляр класса DiscreteRectKeyFrame для резкого уменьшения высоты прямоугольника. Дискретные ключевые кадры, например DiscreteRectKeyFrame, создают резкие изменения значений, т. е. уменьшение высоты происходит быстро и не плавно.

  3. В течение последних двух секунд используется экземпляр класса SplineRectKeyFrame для возврата прямоугольника обратно в исходное положение и к исходному размеру. Ключевые кадры сплайна, например, SplineRectKeyFrame, создают переменный переход от одного значения к другому, в зависимости от значения свойства 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 RectAnimationUsingKeyFrames class to
    /// animate the position and size of a rectangle.
    /// Key frame animations enable you to create complex animations
    /// by specifying multiple destination values
    /// and controlling the animation's interpolation method.
    /// </summary>
    public class RectAnimationUsingKeyFramesExample : Page
    {
        public RectAnimationUsingKeyFramesExample()
        {
            Title = "RectAnimationUsingKeyFrames 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());

            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Orientation = Orientation.Vertical;
            myStackPanel.HorizontalAlignment = HorizontalAlignment.Center;

            //Add the Path Element
            Path myPath = new Path();
            myPath.Stroke = Brushes.Black;
            myPath.Fill = Brushes.LemonChiffon;
            myPath.StrokeThickness = 1;

            // Create a RectangleGeometry to specify the Path data.
            RectangleGeometry myRectangleGeometry = new RectangleGeometry();
            myRectangleGeometry.Rect = new Rect(0, 200, 100, 100);
            myPath.Data = myRectangleGeometry;

            myStackPanel.Children.Add(myPath);

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

            // Create a RectAnimationUsingKeyFrames to
            // animate the RectangleGeometry.
            RectAnimationUsingKeyFrames rectAnimation
                = new RectAnimationUsingKeyFrames();
            rectAnimation.Duration = TimeSpan.FromSeconds(6);

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

            // Animate position, width, and height in first 2 seconds. LinearRectKeyFrame creates
            // a smooth, linear animation between values.
            rectAnimation.KeyFrames.Add(
                new LinearRectKeyFrame(
                    new Rect(600,50,200,50), // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2))) // KeyTime
                );

            // In the next half second, change height to 10. DiscreteRectKeyFrame creates a
            // sudden "jump" between values.
            rectAnimation.KeyFrames.Add(
                new DiscreteRectKeyFrame(
                    new Rect(600, 50, 200, 10), // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.5))) // KeyTime
                );

            // In the final 2 seconds of the animation, go back to the starting position, width, and height.
            // Spline key frames like SplineRectKeyFrame creates a variable transition between values depending
            // on the KeySpline property. In this example, the animation starts off slow but toward the end of
            // the time segment, it speeds up exponentially.
            rectAnimation.KeyFrames.Add(
                new SplineRectKeyFrame(
                    new Rect(0, 200, 100, 100), // Target value (KeyValue)
                    KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4.5)), // KeyTime
                    new KeySpline(0.6, 0.0, 0.9, 0.0) // KeySpline
                    )
                );

            // Set the animation to target the Rect property
            // of the object named "AnimatedRectangleGeometry."
            Storyboard.SetTargetName(rectAnimation, "AnimatedRectangleGeometry");
            Storyboard.SetTargetProperty(
                rectAnimation, new PropertyPath(RectangleGeometry.RectProperty));

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

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

            Content = myStackPanel;
        }
    }
}

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 RectAnimationUsingKeyFrames class to
    ''' animate the position and size of a rectangle.
    ''' Key frame animations enable you to create complex animations 
    ''' by specifying multiple destination values
    ''' and controlling the animation's interpolation method.
    ''' </summary>
    Public Class RectAnimationUsingKeyFramesExample
        Inherits Page
        Public Sub New()
            Title = "RectAnimationUsingKeyFrames 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())

            Dim myStackPanel As New StackPanel()
            myStackPanel.Orientation = Orientation.Vertical
            myStackPanel.HorizontalAlignment = HorizontalAlignment.Center

            'Add the Path Element
            Dim myPath As New Path()
            myPath.Stroke = Brushes.Black
            myPath.Fill = Brushes.LemonChiffon
            myPath.StrokeThickness = 1

            ' Create a RectangleGeometry to specify the Path data.
            Dim myRectangleGeometry As New RectangleGeometry()
            myRectangleGeometry.Rect = New Rect(0, 200, 100, 100)
            myPath.Data = myRectangleGeometry

            myStackPanel.Children.Add(myPath)

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

            ' Create a RectAnimationUsingKeyFrames to
            ' animate the RectangleGeometry.
            Dim rectAnimation As New RectAnimationUsingKeyFrames()
            rectAnimation.Duration = TimeSpan.FromSeconds(6)

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

            ' Animate position, width, and height in first 2 seconds. LinearRectKeyFrame creates
            ' a smooth, linear animation between values.
            rectAnimation.KeyFrames.Add(New LinearRectKeyFrame(New Rect(600,50,200,50), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)))) ' KeyTime -  Target value (KeyValue)

            ' In the next half second, change height to 10. DiscreteRectKeyFrame creates a 
            ' sudden "jump" between values.
            rectAnimation.KeyFrames.Add(New DiscreteRectKeyFrame(New Rect(600, 50, 200, 10), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.5)))) ' KeyTime -  Target value (KeyValue)

            ' In the final 2 seconds of the animation, go back to the starting position, width, and height.  
            ' Spline key frames like SplineRectKeyFrame creates a variable transition between values depending 
            ' on the KeySpline property. In this example, the animation starts off slow but toward the end of 
            ' the time segment, it speeds up exponentially.
            rectAnimation.KeyFrames.Add(New SplineRectKeyFrame(New Rect(0, 200, 100, 100), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4.5)), New KeySpline(0.6, 0.0, 0.9, 0.0))) ' KeySpline -  KeyTime -  Target value (KeyValue)

            ' Set the animation to target the Rect property
            ' of the object named "AnimatedRectangleGeometry."
            Storyboard.SetTargetName(rectAnimation, "AnimatedRectangleGeometry")
            Storyboard.SetTargetProperty(rectAnimation, New PropertyPath(RectangleGeometry.RectProperty))

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

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

            Content = myStackPanel
        End Sub

    End Class
End Namespace
<Page  
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="ThicknessAnimationUsingKeyFrames Example">

  <StackPanel Orientation="Vertical" HorizontalAlignment="Center">

    <Path Stroke="Black" StrokeThickness="1" Fill="LemonChiffon">
      <Path.Data>
        <RectangleGeometry x:Name="myRectangleGeometry" Rect="0,200,100,100" />
      </Path.Data>
      <Path.Triggers>
        <EventTrigger RoutedEvent="Path.Loaded">
          <BeginStoryboard>
            <Storyboard>

              <!-- Animate the Rect property of the RectangleGeometry which causes the
              rectangle to animate its position as well as its width and height. -->
              <RectAnimationUsingKeyFrames
                Storyboard.TargetName="myRectangleGeometry"
                Storyboard.TargetProperty ="Rect"
                Duration="0:0:6" FillBehavior="HoldEnd" RepeatBehavior="Forever">

                <!-- Animate position, width, and height in first 2 seconds. LinearRectKeyFrame creates
                a smooth, linear animation between values. -->
                <LinearRectKeyFrame Value="600,50,200,50" KeyTime="0:0:2" />

                <!-- In the next half second, change height to 10. DiscreteRectKeyFrame creates a 
                sudden "jump" between values. -->
                <DiscreteRectKeyFrame Value="600,50,200,10" KeyTime="0:0:2.5" />

                <!-- In the final 2 seconds of the animation, go back to the starting position, width, and height.  
                Spline key frames like SplineRectKeyFrame creates a variable transition between values depending 
                on the KeySpline property. In this example, the animation starts off slow but toward the end of 
                the time segment, it speeds up exponentially.-->
                <SplineRectKeyFrame Value="0,200,100,100" KeyTime="0:0:4.5" KeySpline="0.6,0.0 0.9,0.00"  />
              </RectAnimationUsingKeyFrames>
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Path.Triggers>
    </Path>

  </StackPanel>
</Page>

Описание полного примера см. в разделе Пример анимации по ключевым кадрам.

См. также