본문 바로가기

   
Programming/WPF

WPF XAML 을 C# Code로, 애니메이션, 스토리보드

반응형

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

 

namespace WPFEx

{

       /// <summary>

       /// Code01.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code01 : Window

       {

             public Code01()

             {

                    InitializeComponent();

             }

 

             private void Window_Loaded(object sender, RoutedEventArgs e)

             {

                    M1();

                    //M2();

 

             }

 

             private void M1()

             {

                    Button btn = new Button();

                    btn.Content = "버튼";

                    btn.Width = 100;

                    btn.Height = 100;

                    btn.RenderTransformOrigin = new Point(0.5, 0.5);

 

                    //Transform : 부모이다(업캐스팅이 가능하도록 부모타입을 만들어 놓았다.)

                    RotateTransform rTrans = new RotateTransform();

                    rTrans.Angle = 30;

 

                    btn.RenderTransform = rTrans;

 

                    grid1.Children.Add(btn);

             }

 

             private void M2()

             {

                    Button btn = new Button();

                    btn.Content = "버튼";

                    btn.Width = 100;

                    btn.Height = 100;

                    btn.RenderTransformOrigin = new Point(0.5, 0.5);

 

                    //1. 회전

                    RotateTransform rTrans = new RotateTransform();

                    rTrans.Angle = 30;

 

 

                    //2. 스케일

                    ScaleTransform sTrans = new ScaleTransform();

                    sTrans.ScaleX = 2;

 

                    //TransformGroup

                    TransformGroup group = new TransformGroup();

                    group.Children.Add(rTrans);

                    group.Children.Add(sTrans);

 

                    btn.RenderTransform = group;//**

 

                    grid1.Children.Add(btn);

             }

 

       }

}

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Windows.Media.Animation;//**스토리보드, 더블애니메이션 등..

 

namespace WPFEx

{

       /// <summary>

       /// Code02.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code02 : Window

       {

             public Code02()

             {

                    InitializeComponent();

             }

 

             private void btn_Click(object sender, RoutedEventArgs e)

             {

                    //C#에서 애니메이션을 생성 -> 실행

                    //1. 2개 이상의 애니메이션을 동시에 제어를 하는 경우

                    // -> 스토리보드가 필요

                    //2. 1개의 애니메이션을 제어하는 경우

                    // -> C#에서는 스토리보드가 필요X

 

                    //버튼은 Width 100 -> 250

 

                    //1. 애니메이션 객체를 생성

                   

                    DoubleAnimation da = new DoubleAnimation();

                    da.From = 100;

                    da.To = 250;

                    da.Duration = new Duration(TimeSpan.FromSeconds(1));

                    //da.RepeatBehavior = new RepeatBehavior(3);

                    da.RepeatBehavior = RepeatBehavior.Forever;

                    da.AutoReverse = true;

                    da.AccelerationRatio = 1;

 

                    //2. 실행 -> ? da가 누구의 어떤 속성을 건드려야 함?

                    //애니메이션의 대상이 되는 객체를 찾아가 객체.BeginAnimation()호출을 해야한다.

                    //의존속성 Button.WidthProperty

                    btn.BeginAnimation(Button.WidthProperty, da);

 

             }

       }

}

 

 


XAML 

<Window x:Class="WPFEx.Code03"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code03" Height="300" Width="300">

 

       <Window.Resources>

             <Style TargetType="{x:Type Button}">

                    <Setter Property="Width" Value="50" />

                    <Setter Property="Height" Value="0" />

                    <Setter Property="Margin" Value="3" />

                    <Setter Property="VerticalAlignment" Value="Top" />

                    <Setter Property="VerticalAlignment" Value="Bottom" />

             </Style>

       </Window.Resources>

 

       <StackPanel Name="stack" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom">

             <Button Content="국어" Name="btnKor" />

             <Button Content="영어" Name="btnEng" />

             <Button Content="수학" Name="btnMath" />

             <Button Content="성적확인" Width="60" Height="30" Click="Button_Click" />

       </StackPanel>

 

</Window>

 

 
 C#  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.IO;

using System.Windows.Media.Animation;//**

 

namespace WPFEx

{

       /// <summary>

       /// Code03.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code03 : Window

       {

             public Code03()

             {

                    InitializeComponent();

             }

 

             private void Button_Click(object sender, RoutedEventArgs e)

             {

                    //1. 파일읽기(ANSI)

                    StreamReader reader = new StreamReader(@"F:\MS닷넷(KH)\WPF\WPFEx\WPFEx\bin\Debug\data.txt", Encoding.Default);

 

                    //2. 버튼의 집합

                    List<Button> btnList = new List<Button>();

                    btnList.Add(btnKor);

                    btnList.Add(btnEng);

                    btnList.Add(btnMath);

 

 

                    //3. 성적 읽기

                    string txt = "";

                    int index = 0;

 

                    while ((txt = reader.ReadLine()) != null)

                    {

                           //MessageBox.Show(txt);

                           double score = double.Parse(txt);

                           btnList[index].Height = score * 2.5;

 

                           //4. 읽어온 성적을 가지고 DoubleAnimation생성

                           DoubleAnimation da = new DoubleAnimation();

 

                           da.From = 0;

                           da.To = score * 2.5;

                           da.Duration = new Duration(TimeSpan.FromSeconds(1));

 

                           //5. 애니메이션 실행

                           btnList[index].BeginAnimation(Button.HeightProperty, da);

 

                           index++;

 

 

                    }

 

             }

       }

}

 

  
 XAML 
 <Window x:Class="WPFEx.Code04"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code04" Height="300" Width="300">

      

       <Window.Resources>

             <Style TargetType="{x:Type TextBlock}">

                    <Setter Property="FontSize" Value="50" />

             </Style>                     

       </Window.Resources>

      

      

       <Button Name="btn" Width="200" Height="200" Click="btn_Click">

             <UniformGrid>

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

                    <TextBlock Text="" />

             </UniformGrid>

       </Button>

      

</Window>

 
 C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.IO;

using System.Windows.Media.Animation;//**

 

namespace WPFEx

{

       /// <summary>

       /// Code04.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code04 : Window

       {

             public Code04()

             {

                    InitializeComponent();

             }

 

             private void btn_Click(object sender, RoutedEventArgs e)

             {

                    Random rnd = new Random();

                    RotateTransform rt = new RotateTransform();

                    btn.RenderTransformOrigin = new Point(0.5, 0.5);

 

                    btn.RenderTransform = rt;

 

                    //원하는 각도

                    //rt.Angle = 50;

 

                    //애니메이션

                    DoubleAnimation da = new DoubleAnimation();

                    //da.From = 0;

                    //da.To = rnd.Next(0, 1000);

                    da.By = rnd.Next(0, 1000);

                    da.Duration = new Duration(TimeSpan.FromSeconds(rnd.Next(1, 10)));

 

                    //실행(**)

                    rt.BeginAnimation(RotateTransform.AngleProperty, da);

             }

       }

}

 



같은 형태의 디자인에서 C#으로 스토리 보드 만들기
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.IO;

using System.Windows.Media.Animation;//**

 

namespace WPFEx

{

       /// <summary>

       /// Code04.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code04 : Window

       {

             public Code04()

             {

                    InitializeComponent();

             }

 

             private void btn_Click(object sender, RoutedEventArgs e)

             {

                    //1. 트랜스폼 생성

                    RotateTransform rt = new RotateTransform();

                    btn.RenderTransformOrigin = new Point(0.5, 0.5);

                    btn.RenderTransform = rt;

 

                    //2. 스토리보드 생성<Storyboard>

                    Storyboard story = new Storyboard();

 

                    //3. 애니메이션 생성 <DoubleAnmation>

                    DoubleAnimation da = new DoubleAnimation();

                    da.From = 0;

                    da.To = 3600;

                    da.Duration = new Duration(TimeSpan.FromSeconds(2));

 

                    //4. 스토리보드의 자식 -> 애니메이션

                    story.Children.Add(da);//여러개 더추가

 

                    //5. Storyboard.TargetName = "btn"

                    //   Storyboard.TargetProperty = "RenderTransform.Angle"

                    Storyboard.SetTargetName(da, btn.Name);

                    Storyboard.SetTargetProperty(da, new PropertyPath("RenderTransform.Angle"));

 

                    //6. <BeginStoryboard>

                    //어떤 컨테이너 안에 있는 컨트롤이냐?

                    story.Begin(this);

             }

       }

}

 

 


XAML 

<Window x:Class="WPFEx.Code05"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code05" Height="650" Width="700">

 

       <Canvas>

             <TextBlock Text="" FontSize="30" Canvas.Left="340" Canvas.Top="10" Foreground="Gold" />

             <Image Source="F:\MS닷넷(KH)\WPF\WPFEx\WPFEx\bin\Debug\images\One.gif" Width="468" Height="468" Canvas.Left="116" Canvas.Top="80" Name="one" RenderTransformOrigin="0.5,0.5" MouseDown="one_MouseDown">

 

                    <Image.RenderTransform>

                           <RotateTransform />

                    </Image.RenderTransform>

 

             </Image>

       </Canvas>

 

</Window>

 

 

<Window x:Class="WPFEx.Code05"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"




C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Windows.Media.Animation;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

 

namespace WPFEx

{

       /// <summary>

       /// Code05.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code05 : Window

       {

             public Code05()

             {

                    InitializeComponent();

             }

 

             private void one_MouseDown(object sender, MouseButtonEventArgs e)

             {

                    Random rnd = new Random(DateTime.Now.Millisecond);

 

                    Storyboard story = new Storyboard();

                    DoubleAnimation da = new DoubleAnimation();

                    da.From = 0;

                    da.To = rnd.Next(10000, 50000);

                    da.Duration = new Duration(TimeSpan.FromMilliseconds((double)da.To / 5.0D));

                    da.DecelerationRatio = 0.8;

                    story.Children.Add(da);

 

                    Storyboard.SetTargetName(da, one.Name);

                    Storyboard.SetTargetProperty(da, new PropertyPath("RenderTransform.Angle"));

 

                    story.Completed += new EventHandler(story_Completed);

                    story.Begin(this);

 

                   

             }

 

             void story_Completed(object sender, EventArgs e)

             {

                    //회전각? -> 선택된 누가?

                    MessageBox.Show("선택");

             }

       }

}

 

  


XAML 

<Window x:Class="WPFEx.Code06"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code06" Height="300" Width="800" Loaded="Window_Loaded">

      

       <Window.Resources>

             <Storyboard x:Key="story">

                    <DoubleAnimation />

             </Storyboard>

       </Window.Resources>

      

    <Grid>

             <Grid.RowDefinitions>

                    <RowDefinition Height="230" />

                    <RowDefinition Height="*" />

             </Grid.RowDefinitions>

             <Grid.Children>

                    <Canvas Name="canvas1">

                          

                    </Canvas>

                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Row="1">

                           <Button Content="Left" Width="100" Height="30" Click="Button_Click" />

                           <Button Content="Right" Width="100" Height="30" Click="Button_Click" />

                    </StackPanel>

             </Grid.Children>

       </Grid>

</Window>

 

 


C#
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Windows.Media.Animation;

 

namespace WPFEx

{

       /// <summary>

       /// Code06.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code06 : Window

       {

             public Code06()

             {

                    InitializeComponent();

             }

 

             private void Window_Loaded(object sender, RoutedEventArgs e)

             {

                    //버튼(이미지) 여러개 생성 -> 캔버스

                    double left = -770;

 

                    for (int i = 0; i < 20; i++)

                    {

                           Button btn = new Button();

                           btn.Width = 100;

                           btn.Height = 200;

 

                           Canvas.SetLeft(btn, left);

                           Canvas.SetTop(btn, 15);

 

                           left += 110;

 

                           //애니메이션을 위한 추가 작업(*****)

                           //동적으로 애니메이션을 적용할때 btn.RegisterName(btn.Name, btn); 등록과정을 거쳐야지만 애니메이션에서 인식할수 있다.

                          

                           btn.Name = "btn" + i;

 

                           canvas1.Children.Add(btn);

                          

                           //화면에 추가가 된 후에 가능!!!

                           btn.RegisterName(btn.Name, btn);

 

 

                          

                    }

 

 

             }

 

             private void Button_Click(object sender, RoutedEventArgs e)

             {

                    //어느 버튼?

                    Button btn = e.Source as Button;

 

                    //이동 수치

                    double move = 660;

 

                    if (btn.Content.ToString() == "Left")

                           //MessageBox.Show("왼쪽");

                           move *= -1;

 

                    //버튼 -> 애니메이션(DoubleAnimation) -> 이동(Canva.Left)

                    //1. Canvas자체를 움직이기

                    //2. 버튼x20개를 움직이기

 

                    for (int i = 0; i < canvas1.Children.Count; i++)

                    {

                           Button b = canvas1.Children[i] as Button;

 

                           //Storyboard story = new Storyboard();

                           //DoubleAnimation da = new DoubleAnimation();

 

                           Storyboard story = this.Resources["story"] as Storyboard;

                           DoubleAnimation da = story.Children[0] as DoubleAnimation;

 

                           da.By = move;//660? ~ -660?

                           da.Duration = new Duration(TimeSpan.FromSeconds(3));

                           da.RepeatBehavior = RepeatBehavior.Forever;

 

                           Storyboard.SetTargetName(da, b.Name);

                          Storyboard.SetTargetProperty(da, new PropertyPath("(Canvas.Left)"));

 

                           story.Begin(this);

                    }

             }

       }

}

 

 


XAML
 
 <Window x:Class="WPFEx.Code09"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code09" Height="600" Width="800" Loaded="Window_Loaded">

      

       <ListBox Name="listBox1" ScrollViewer.HorizontalScrollBarVisibility="Disabled" VerticalAlignment="Top">

             <ListBox.ItemsPanel>

                    <ItemsPanelTemplate>

                           <WrapPanel />

                    </ItemsPanelTemplate>

             </ListBox.ItemsPanel>

       </ListBox>

</Window>



C#
  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

using System.Windows.Media.Animation;

 

namespace WPFEx

{

       /// <summary>

       /// Code09.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code09 : Window

       {

 

             private Button oldBtn;

 

             public Code09()

             {

                    InitializeComponent();

             }

 

             private void Window_Loaded(object sender, RoutedEventArgs e)

             {

                    for (int i = 0; i < 100; i++)

                    {

                           Button btn = new Button();

                           btn.Content = i.ToString();

                           btn.Width = 100;

                           btn.Height = 20;

                           btn.Margin = new Thickness(4);

                           btn.VerticalAlignment = VerticalAlignment.Top;

                           btn.Click += new RoutedEventHandler(btn_Click);

                           listBox1.Items.Add(btn);

                    }

             }

 

             void btn_Click(object sender, RoutedEventArgs e)

             {

                    //1개의 버튼을 클릭

                    Button btn = e.Source as Button;

 

                    //이전에 눌렸떤 버튼이 있는지?

                    if (this.oldBtn != null && btn != this.oldBtn)

                    {

                           if (this.oldBtn.Height != 20)

                           {

                                 DoubleAnimation da2 = new DoubleAnimation();

                                 da2.From = 150;

                                 da2.To = 20;

                                 da2.Duration = new Duration(TimeSpan.FromSeconds(0.5));

                                

                                 this.oldBtn.BeginAnimation(Button.HeightProperty, da2);

                           }

                    }

                   

 

                    DoubleAnimation da = new DoubleAnimation();

 

                    if (btn.Height == 20)

                    {

                           da.From = 20;

                           da.To = 150;

                           //da.By = 130;

                    }

                    else

                    {

                           da.From = 150;

                           da.To = 20;

                           //da.By = -130;

                    }

 

                    da.Duration = new Duration(TimeSpan.FromSeconds(0.1));

                    btn.BeginAnimation(Button.HeightProperty, da);

 

                    this.oldBtn = btn; //지금 누른 버튼

             }

       }

}

 

 




 XAML 
<
Window x:Class="WPFEx.Code08"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Code08" Height="500" Width="800">

      

       <DockPanel>

             <StackPanel Orientation="Horizontal" Height="30" DockPanel.Dock="Bottom" HorizontalAlignment="Center" Margin="5">

                    <Button Width="100" Content="지우기" Click="Button_Click" />

                    <Button Width="100" Content="저장하기" Click="Button_Click_1" />

                    <Button Width="100" Content="블러오기" Click="Button_Click_2" />

             </StackPanel>

             <InkCanvas Name="ink" />

       </DockPanel>

      

</Window>

 

      

C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

 

using System.IO;

using System.Windows.Markup;

using System.Windows.Ink;

using Microsoft.Win32;

 

namespace WPFEx

{

       /// <summary>

       /// Code08.xaml에 대한 상호 작용 논리

       /// </summary>

       public partial class Code08 : Window

       {

             public Code08()

             {

                    InitializeComponent();

             }

 

             private void Button_Click(object sender, RoutedEventArgs e)

             {

                    //지우기

                    ink.Strokes.Clear();

             }

 

             private void Button_Click_1(object sender, RoutedEventArgs e)

             {

                    //저장하기(*.xaml)

                    //OS의 대화상자를 가져와서 사용

                    SaveFileDialog save = new SaveFileDialog();

                    save.Filter = "잉크파일|*.ink";

 

                    if ((bool)save.ShowDialog() == true)

                    {

                           //this.Title = save.FileName;

                           File.WriteAllText(save.FileName, XamlWriter.Save(ink.Strokes));

                    }

 

             }

 

             private void Button_Click_2(object sender, RoutedEventArgs e)

             {

                    //불러오기

                    OpenFileDialog open = new OpenFileDialog();

                    open.Filter = "잉크파일|*.ink";

 

                    if ((bool)open.ShowDialog() == true)

                    {

                           ink.Strokes = (StrokeCollection)XamlReader.Load(File.OpenRead(open.FileName));

                    }

             }

       }

}

 

       

 

 

반응형