본문 바로가기

C#,WPF

[WPF] Animation 예제(회전)


도형을 회전시켜보도록 하겠다.

XAML 코드로 만들어진 도형을 클릭이벤트를 받아

회전 메소드를 실행시킨다.


<XAML 코드>
 
Grid 내에 Rectangle(도형) 과 Button(버튼) 을 생성하였다.
클릭이벤트는 rotate 를 실행하도록 짜여져 있다.

  <Window x:Class="WpfApplication2.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525">
    <Grid>
       <Rectangle Height="56" HorizontalAlignment="Left" Margin="204,104,0,0" Name="rectangle1"
               
 Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FFFA0000" />
       <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="21,276,0,0"
                 Name="button1"    VerticalAlignment="Top" Width="75" Click="rotate" />
    </Grid>
</
Window>




<비하인드 코드>

 네임스페이스 사용
using System; //TimeSpan 사용
using System.Text;
using System.Windows;
using System.Windows.Controls; // Image 컨트롤 사용
using System.Windows.Media; // Animation 사용
using System.Windows.Media.Animation; // Animation 사용



Mainwindow 클래스내에
메소드를 넣는다.

private void rotate(object sender, RoutedEventArgs e)
{
DoubleAnimation da = new DoubleAnimation();
da.From = 0;
da.To = 360;
da.Duration = new Duration(TimeSpan.FromSeconds(3));
da.RepeatBehavior = RepeatBehavior.Forever;
RotateTransform rt = new RotateTransform();
rectangle1.RenderTransform = rt;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
}



DoubleAnimation 은 지정된 Duration(시간) 동안 선형 보간을 사용하여 두 대상 값 사이에서
Double 속성값에 애니메이션을 적용한다.

선형보간이란 간단히 말해서 애니메이션 프레임이 넘어가는 사이를 좀더 부드럽게 이미지화 해준다는  것이다.
선형은 비선형과 다르게 규칙적이므로, 임의규칙적으로 움직이는 오브젝트에는 크게 적용하기 어렵다.



만약 도형 대신 이미지를 넣고싶다면
xaml 코드에 Image 를 넣어주고 MouseLeftButtonDown="rotate" 를 호출해주면 된다.
(나머지는 동일)