首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發 WPF/Silverlight 動畫與遊戲系列教程(五)實現 2D 人物動畫 ②(一)—— 圖片截取法實作

     編輯:關於C語言

圖片截取法

以主角向右施法動畫為例。先用 Photoshop 將 10 幀 150×150 圖片合併為一張 1500×150 大圖(見下圖),存放專案 bin\Debug 目錄(BitmapFrame.Create 相對路徑僅識別此資料夾)。

合併大圖清晰展現施法全過程。

存放路徑示意。

後台 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(@"Player\PlayerMagic.png", count * 150, 0, 150, 150);
    count = count == 9 ? 0 : count + 1;
}

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));
}

使用 CroppedBitmap 從大圖裁切單幀,Int32Rect 指定裁切區域。避免大量小檔案 I/O,提升效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved