WPF之基于路径的动画

原文: WPF之基于路径的动画

  不是突然想到要做一个路径动画的,是今天谈业务需求的时候偶然谈到的,

  一艘船从一个国家到另外一个国家,沿着一条固定的路线前进,就是一个简单的动画效果,以前貌似在书上看到过,所以自己也来做一个。

  在网上搜资料发现都是给你看看代码,或者边写边看代码。

  认为还是要先研究一下这个东西要如何实现吧,参考资料是《WPF编程宝典》。

  其实中心思想还是很简单的,主要是设置对象的Storyboard中DoubleAnimationsUsingPath的PathGeometry属性。

  下面这个实例是去则WPF变成宝典之中,因为不太复杂,就随便看看吧~

  这个例子里面是对image这个对象进行操作,所谓动画就是去根据路径去改变image的位置,就是Canvas.Left和Canvas.Top,给PathGeometry绑定设定好的路径,然后指定Source是对应的XY轴。

  

<Window x:Class="Animation.PathBasedAnimation"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="PathBasedAnimation" Height="381.6" Width="521.6"
    >
  
  <Window.Resources>
    <PathGeometry x:Key="path">
      <PathFigure IsClosed="True">
        <ArcSegment Point="100,200" Size="15,10" SweepDirection="Clockwise"></ArcSegment>
        <ArcSegment Point="400,50" Size="5,5" ></ArcSegment>
      </PathFigure>
    </PathGeometry>
  </Window.Resources>
  <Window.Triggers>
    <EventTrigger RoutedEvent="Window.Loaded">
      <EventTrigger.Actions>
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimationUsingPath Storyboard.TargetName="image"
                                      Storyboard.TargetProperty="(Canvas.Left)"
                                        PathGeometry="{StaticResource path}"
                                      Duration="0:0:5" RepeatBehavior="Forever" Source="X" />
            <DoubleAnimationUsingPath Storyboard.TargetName="image"
                                      Storyboard.TargetProperty="(Canvas.Top)"
                                     PathGeometry="{StaticResource path}"
                                      Duration="0:0:5" RepeatBehavior="Forever" Source="Y" />
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger.Actions>
    </EventTrigger>
  </Window.Triggers>
  <Canvas Margin="10">
    <Path Stroke="Red" StrokeThickness="1" Data="{StaticResource path}" Canvas.Top="10" Canvas.Left="10">      
    </Path>
    <Image Name="image">
      <Image.Source>
        <DrawingImage>
          <DrawingImage.Drawing>
            <GeometryDrawing Brush="LightSteelBlue">
              <GeometryDrawing.Geometry>
                <GeometryGroup>
                  <EllipseGeometry Center="10,10" RadiusX="9" RadiusY="4" />
                  <EllipseGeometry Center="10,10" RadiusX="4" RadiusY="9" />
                </GeometryGroup>
              </GeometryDrawing.Geometry>
              <GeometryDrawing.Pen>
                <Pen Thickness="1" Brush="Black" />
              </GeometryDrawing.Pen>
            </GeometryDrawing>
          </DrawingImage.Drawing>
        </DrawingImage>
      </Image.Source>
    </Image>
  </Canvas>
</Window>

  完全不难,但是我自己还是没有记得,所以写了一篇短短的Blog.

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9472853.html