提高 C# Windows 窗體中的點陣圖操作速度:SetPixel 與 GetPixel 的替代方案
SetPixel
和 GetPixel
在 C# Windows 窗體應用程式中進行點陣圖操作是出了名的慢。 本文探討了高性能替代方案。
DirectBitmap 類別:一種高階方法
DirectBitmap
類別提供對位圖資料的直接訪問,繞過 LockBits
和 SetPixel
的效能開銷:
public class DirectBitmap : IDisposable { // ... public void SetPixel(int x, int y, Color colour) { int index = x + (y * Width); int col = colour.ToArgb(); Bits[index] = col; } public Color GetPixel(int x, int y) { int index = x + (y * Width); int col = Bits[index]; Color result = Color.FromArgb(col); return result; } // ... }
這種直接記憶體操作顯著減少了記憶體分配,從而加快了處理速度。
帶位元組的原始像素資料:更快
為了獲得最終速度,請使用位元組而不是整數表示像素資料:
Bits = new byte[width * height * 4];
每個像素現在使用 4 個位元組 (ARGB)。 請記得相應調整 SetPixel
和 GetPixel
。
DirectBitmap 的優點:
Dispose()
進行高效能記憶體管理。 注意事項:
Graphics
物件無縫整合。 效能基準:
效能測試證明了DirectBitmap
的明顯優勢:
Method | 4x4 | 16x16 | 64x64 | 256x256 | 1024x1024 | 4096x4096 |
---|---|---|---|---|---|---|
DirectBitmap | 2 | 28 | 668 | 8219 | 178639 | |
LockBits | 2 | 3 | 33 | 670 | 9612 | 197115 |
SetPixel | 45 | 371 | 5920 | 97477 | 1563171 | 25811013 |
透過實作這些最佳化技術,C# 開發人員可以顯著提高 Windows 窗體應用程式中點陣圖操作的效率。
以上是除了 SetPixel 和 GetPixel 之外,如何提高 C# Windows 窗體應用程式中的點陣圖操作效能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!