C# Windows フォームでのビットマップ操作速度の向上: SetPixel および GetPixel の代替手段
SetPixel
と GetPixel
は、C# Windows Forms アプリケーションでのビットマップ操作が遅いことで有名です。 この記事では、高性能の代替手段について説明します。
DirectBitmap クラス: 優れたアプローチ
DirectBitmap
クラスは、LockBits
と SetPixel
のパフォーマンス オーバーヘッドをバイパスして、ビットマップ データへの直接アクセスを提供します。
<code class="language-csharp">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; } // ... }</code>
この直接メモリ操作によりメモリ割り当てが大幅に削減され、処理の高速化につながります。
バイトを含む生のピクセル データ: さらに高速
究極の速度を実現するには、整数の代わりにバイトを使用してピクセル データを表します。
<code class="language-csharp">Bits = new byte[width * height * 4];</code>
各ピクセルは 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 中国語 Web サイトの他の関連記事を参照してください。