技术开发 频道

开发Silverlight游戏教程:实现2D人物动画

  O K,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("PlayerMagic.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)

);

}

    从上面代码可以看出前半部分和上一节的一样,这里就不累述了,精华就在后面的cutImage方法,该方法可谓集天地之精华,日月之灵气。。。扯远了,该方法的详细描述已经写在上面,大家可以慢慢体会应该不难。

    有了该尚方宝剑,那么大家应该也多少有点感觉了吧,最后在dispatcherTimer_Tick方法中,我们即调用该方法实现时时的图片截取来循环生成动画,Ctrl+F5看看,呵呵,主角会放魔法啦!

原文地址:http://www.cnblogs.com/alamiye010/archive/2009/06/17/1505335.html

0
相关文章