| 方法 | 圖片切換法 (第 4 章) | 圖集裁切法 (本章) |
| 素材形式 | 每幀獨立檔案 (0.png~7.png) | 單一大圖集 (1500×150) |
| 載入方式 | 逐幀 new BitmapImage(Uri) | 一次載入圖集,CroppedBitmap 裁切 |
| IO 效能 | 頻繁磁碟/網路請求 | 單次請求,記憶體裁切極快 |
| Silverlight 適用 | ✓ 唯一可行 | ✗ 需 WriteableBitmap 支援 |
| WPF 推薦度 | ★★☆ | ★★★★★ |
圖集製作流程
- 準備 10 幀 150×150 單獨幀圖(例:向右施法動畫)
- Photoshop 橫向拼接為 1500×150 大圖
PlayerMagic.png
- 放入專案
bin\Debug\Player\ 目錄(BitmapFrame.Create 相對路徑僅識別此資料夾)
核心裁切方法:CroppedBitmap
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)
);
}
Int32Rect(x,y,width,height) 指定裁切區域,回傳 BitmapSource 可直接指派給 Image.Source,無需重新解碼像素資料,效能極高。
DispatcherTimer 幀驅動邏輯
int count = 1;
Image Spirit;
public Window5()
{
InitializeComponent();
Spirit = new Image { Width = 150, Height = 150 };
Carrier.Children.Add(Spirit);
var dt = new DispatcherTimer();
dt.Tick += (s,e) => {
Spirit.Source = CutImage(@"Player\PlayerMagic.png", count * 150, 0, 150, 150);
count = count == 9 ? 0 : count + 1;
};
dt.Interval = TimeSpan.FromMilliseconds(150);
dt.Start();
}
每 150ms 裁切下一幀 (x 偏移 150px),第 10 幀歸零循環。運行效果:角色流暢播放施法動畫。
進階:批次合成大圖集函數
若有 488 張 150×150 素材,可編寫函數自動合成 9150×1200 超大圖集(<3 秒),關鍵在於:
- 檔名有序規律(如
0.png~487.png)
- 使用
DrawingVisual + RenderTargetBitmap 離屏渲染合成
- 輸出 PNG 保留透明通道
此技術在第 17 章 ComposeImage 中完整實現。
平台選型建議
- Silverlight:受限於沙箱與下載體積,只能用圖片切換法,並建議壓縮幀數 (≤5) 與解析度。
- WPF:強烈推薦圖集裁切法,靈活支援高幀率、高解析度、動態動作切換,且可預先合成減少部署檔案數。
下章預告
下一章將融合幀動畫與位移動畫:DispatcherTimer 驅動幀播放,Storyboard 驅動座標位移,實現「點擊移動 + 跑步動畫」的完整角色移動系統,並分析三大缺憾(動作狀態機、腳底定位、八方向)的解決路徑。
- 上一篇文章: WPF/Silverlight 遊戲開發教程 (6):完美移動 — 幀動畫與位移動畫融合、三大缺憾與解決路徑
- 下一篇文章: WPF/Silverlight 遊戲開發教程 (4):2D 角色動畫實作一 — 圖片切換法、DispatcherTimer 幀驅動、素材標準化
Copyright ©
程式碼之家 All Rights Reserved