首頁 > 後端開發 > C++ > 除了 SetPixel 和 GetPixel 之外,如何提高 C# Windows 窗體應用程式中的點陣圖操作效能?

除了 SetPixel 和 GetPixel 之外,如何提高 C# Windows 窗體應用程式中的點陣圖操作效能?

Barbara Streisand
發布: 2025-01-19 02:36:08
原創
898 人瀏覽過

How Can I Improve Bitmap Manipulation Performance in C# Windows Forms Apps Beyond SetPixel and GetPixel?

提高 C# Windows 窗體中的點陣圖操作速度:SetPixel 與 GetPixel 的替代方案

SetPixelGetPixel 在 C# Windows 窗體應用程式中進行點陣圖操作是出了名的慢。 本文探討了高性能替代方案。

DirectBitmap 類別:一種高階方法

DirectBitmap 類別提供對位圖資料的直接訪問,繞過 LockBitsSetPixel 的效能開銷:

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)。 請記得相應調整 SetPixelGetPixel

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板