C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(五)2010-01-25 博客园 深蓝色右手C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(五)实现2D人物动画②第二种方法我称之为图片截取法,准备工作:这里我以创建主角向右方向施法动画为例。首先需要将10帧150*150的图片通过Photoshop或其他方式合成为一张1500*150的大图,如下图:

从图上可以很清晰的看出主角的整个流畅的施法流程。然后将这张图片保存到项目文件夹中的binDebug文件夹中,如下图:

为什么必须放在这呢?因为后面的代码中BitmapFrame.Create()函数调用相对路径图片只认该文件夹,为什么?问MSOK,xaml代码仍旧和前面章节的一样,那么接下来就是后台C#代码了:
Image Spirit;int count = 1;public Window5() {InitializeComponent();Spirit = new Image();Spirit.Width = 150;Spirit.Height = 150;Carrier.Children.Add(Spirit);DispatcherTimer dispatcherTimer = new DispatcherTimer();dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);dispatcherTimer.Interval = TimeSpan.FromMilliseconds(150);dispatcherTimer.Start();}private void dispatcherTimer_Tick(object sender, EventArgs e) {Spirit.Source = cutImage(@"PlayerPlayerMagic.png", count * 150, 0, 150, 150);count = count == 9 ? 0 : count + 1;}/// <summary>/// 截取图片/// </summary>/// <param name="imgaddress">文件名(包括地址+扩展名)</param>/// <param name="x">左上角点X</param>/// <param name="y">左上角点Y</param>/// <param name="width">截取的图片宽</param>/// <param name="height">截取的图片高</param>/// <returns>截取后图片数据源</returns>private BitmapSource cutImage(string imgaddress, int x, int y, int width, int height) {return new CroppedBitmap(BitmapFrame.Create(new Uri(imgaddress, UriKind.Relative)), new Int32Rect(x, y, width, height) );}