繪製是圖形引擎核心。XNA 使用 SpriteBatch 繪製 Sprite(精靈),外觀由 Texture2D 等紋理決定。
將圖片、模型、聲音等素材透過 Content Pipeline 於編譯期轉為 XNA 可識別格式。專案預設 Content 資料夾存放素材,各素材有唯一 AssetName。
Texture2D texture = Content.Load<Texture2D>(@"Image\logo"); // 在 LoadContent 中呼叫
兩種方式:圖片本身透明背景,或將透明區設為純洋紅色(255,0,255)。需 SpriteBlendMode.AlphaBlend(預設)。
預設按呼叫順序決定遮蓋關係。可在 Draw 指定 layerDepth(0~1)控制繪製順序。
protected override void Draw(GameTime gameTime) {
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
spriteBatch.Draw(...);
spriteBatch.End();
base.Draw(gameTime);
}
GraphicsDevice.Clear() 清除背景SpriteBatch.Begin() 通知顯示卡準備繪製Draw() 繪製所有元件SpriteBatch.End() 結束繪製SpriteBlendMode:色彩混合模式(預設 AlphaBlend)SpriteSortMode:排序模式(關聯層深度)SaveStateMode:是否保存圖形裝置狀態TransformMatrix:旋轉、縮放變換矩陣Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle,
Color color, float rotation, Vector2 origin, float scale,
SpriteEffects effects, float layerDepth)
追蹤局部變更需複雜管理器,且移動 Sprite 會露出被遮擋物件,連鎖效應極難處理。每幀全螢幕重繪反而簡單高效。
下一節將講解幀率相關知識。