다음을 통해 공유


방법: 키 프레임을 사용하여 사각형에 애니메이션 효과 주기

업데이트: 2007년 11월

이 예제에서는 키 프레임을 사용하여 RectangleGeometryRect 속성에 애니메이션 효과를 주는 방법을 보여 줍니다.

예제

다음 예제에서는 RectAnimationUsingKeyFrames 클래스를 사용하여 RectangleGeometryRect 속성에 애니메이션 효과를 줍니다. 이 애니메이션에서는 다음과 같은 방식으로 세 가지 키 프레임을 사용합니다.

  1. 처음 2초 동안은 LinearRectKeyFrame 클래스의 인스턴스를 사용하여 사각형의 위치, 너비 및 높이를 점진적으로 변화시키는 애니메이션 효과를 적용합니다. LinearRectKeyFrame과 같은 선형 키 프레임에서는 값 간에 부드러운 선형 전환 효과를 만듭니다.

  2. 다음 0.5초가 끝날 무렵에는 DiscreteRectKeyFrame 클래스의 인스턴스를 사용하여 사각형의 높이를 급격하게 줄입니다. DiscreteRectKeyFrame과 같은 불연속 키 프레임에서는 값 간에 급격한 변경 효과를 만듭니다. 즉, 높이가 눈에 띌 정도로 갑자기 감소합니다.

  3. 마지막 2초 동안은 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;
        }

    }
}
<Page  
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://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>

전체 샘플을 보려면 KeyFrame 애니메이션 샘플을 참조하십시오.

참고 항목

작업

KeyFrame 애니메이션 샘플

개념

키 프레임 애니메이션 개요

참조

RectangleGeometry

Rect

RectAnimationUsingKeyFrames

기타 리소스

키 프레임 애니메이션 방법 항목