[英]How to optimize Form repaint
嘗試編寫一個簡單的 2D 游戲。 這樣做:
public interface GameObject
{
Bitmap Picture { get; }
int OffsetX { get; }
int OffsetY { get; }
}
此處 Picture 屬性返回應為當前 object 繪制的圖片。
public static class Game
{
public class MapIndexer
{
public GameObject this[int x, int y]
{
get => map[y, x];
set => map[y, x] = value;
}
}
private static MapIndexer indexer;
public static MapIndexer Map
{
get => indexer ?? (indexer = new MapIndexer());
}
static GameObject[,] map = new GameObject[,]
{
{ null, null, null },
{ null, null, null },
{ null, null, null }
};
public static int MapWidth
{
get => map.GetLength(1);
}
public static int MapHeight
{
get => map.GetLength(0);
}
}
包含 Map 索引器並用於進一步開發的游戲 class。 [y, x] 索引是像笛卡爾坐標一樣訪問 Map ,否則我會得到倒置的尺寸。 數組中的 NULL 只是一個填充物(即我的游戲中的草,它什么都不做,只需要填充 map,所以我認為沒有理由為它創建一個單獨的 class)。 還從 GameObject 接口創建了一個簡單的 Player class ,它只返回要繪制的圖片。 這是實際的油漆代碼:
private void Form1_Paint(object sender, PaintEventArgs e)
{
for (int y = 0; y < Game.MapHeight; y++)
for (int x = 0; x < Game.MapWidth; x++)
{
e.Graphics.DrawImage(Properties.Resources.Grass, new Point(x * size, y * size));
if (Game.Map[x, y] is not null)
e.Graphics.DrawImage(Game.Map[x, y].Picture, new Point(x * size + Game.Map[x, y].OffsetX, y * size + Game.Map[x, y].OffsetY));
}
}
所以當我做一些動作時,我會使表單無效並獲得下一幀。 對我來說看起來很奇怪,實際上是因為在執行動作時,每次重繪操作時畫面都會閃爍。 測試用的 animation 是玩家移動,每 200ms 發生一次,並不多。 所以問題是:如何優化繪圖使其看起來很流暢,或者我的代碼設計實際上一開始就很糟糕?
您遇到的效果與性能並沒有真正的關系。 您所看到的很可能是在重繪之前清除屏幕的效果。 您應該研究一個稱為“雙緩沖”的概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.