Silverlight动画基础
以下介绍的是两种silverlihgt中的Storyboard的用法:
1.xaml定义动画
1.1:xaml的动画定义,请注意Storyboard的名字是"Storyboard1"
1: <UserControl.Resources>
2: <Storyboard x:Name="Storyboard1">
3: <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="myrect" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
4: <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
5: <SplineDoubleKeyFrame KeyTime="00:00:01" Value="143"/>
6: </DoubleAnimationUsingKeyFrames>
7: <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="myrect" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
8: <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
9: <SplineDoubleKeyFrame KeyTime="00:00:01" Value="9"/>
10: </DoubleAnimationUsingKeyFrames>
11: </Storyboard>
12: </UserControl.Resources>
13: <Grid x:Name="LayoutRoot" Background="White">
14: <Rectangle Height="68" HorizontalAlignment="Left" Margin="116,45,0,0" VerticalAlignment="Top" Width="82" Fill="#FFF0DA47" Stroke="#FF000000" x:Name="myrect" RenderTransformOrigin="0.5,0.5">
15: <Rectangle.RenderTransform>
16: <TransformGroup>
17: <ScaleTransform/>
18: <SkewTransform/>
19: <RotateTransform/>
20: <TranslateTransform/>
21: </TransformGroup>
22: </Rectangle.RenderTransform>
23: </Rectangle>
24: <Button Height="42" HorizontalAlignment="Stretch" Margin="116,0,192,97" VerticalAlignment="Bottom" Content="Button" x:Name="bt"/>
25: </Grid>
1.2调用方式,在.cs文件中
1: public Page()
2: {
3: InitializeComponent();
4: bt.Click += new RoutedEventHandler(bt_Click);
5: }
6:
7: void bt_Click(object sender, RoutedEventArgs e)
8: {
9: Storyboard1.Begin();
10: }
调用Begin()方法即可,还可以通过设设置RepeatBehavior的值为:Forever或者重复的次数让动画重复执行。
2.用c#创建动画
2.1先定义一些元素用来给动画控制,以下是xaml页的内容:
1: <Grid x:Name="LayoutRoot" Background="White">
2: <Rectangle Height="68" HorizontalAlignment="Left" Margin="116,45,0,0" VerticalAlignment="Top" Width="82" Fill="#FFF0DA47" Stroke="#FF000000" x:Name="myrect" RenderTransformOrigin="0.5,0.5" />
3: <Button Height="42" HorizontalAlignment="Stretch" Margin="116,0,192,97" VerticalAlignment="Bottom" Content="Button" x:Name="bt"/>
4: </Grid>
2.2创建代码,以下是cs文件内容
1: public Page()
2: {
3: InitializeComponent();
4: bt.Click += new RoutedEventHandler(bt_Click);
5: }
6:
7: void bt_Click(object sender, RoutedEventArgs e)
8: {
9: //实例化一个点到点动画,命名为da
10: DoubleAnimation da = new DoubleAnimation();
11: //开始参数为1
12: da.From = 1;
13: //结束参数为0
14: da.To = 0;
15:
16: //实例化Storyboard,动画的载体,命名为sb
17: Storyboard sb = new Storyboard();
18: //设定动画与被控控件的关联
19: Storyboard.SetTarget(da, myrect);
20: //设定动画要控制的波控控件的属性,这里是控件透明度
21: Storyboard.SetTargetProperty(da, new PropertyPath("(UIElement.Opacity)"));
22:
23: //把动画添加到Storyboard中
24: sb.Children.Add(da);
25: //开始播放
26: sb.Begin();
27: }