C#优化位图字符绘制算法

Optimizing a bitmap character drawing algorithm in C#

有没有办法优化这个: 一个字符存储在 "matrix" 个字节中,大小为 9x16,为了示例起见,我们称它为 character。 字节可以是值 10 ,分别表示绘制前景和绘制背景。 XY 变量是整数,表示用于 SetPixel() 函数的 X 和 Y 坐标。 BGFG分别代表背景色和前景色,都是Color.

的类型

算法本身的绘图部分如下所示:

for(int i=0;i<16;i++)
{
    for(int j=0;j<9;j++)
    {
        if(character[i][j] == 1)
        {
            SetPixel(X,Y,BG);
        }
        else
        {
            SetPixel(X,Y,FG);
        }
        X++;
    }
    X=0;
    Y++;
}

稍后,X 增加 9,Y 设置回 0。 这个算法的问题是,当调用它来绘制一个字符串(许多字符顺序)时,它非常慢。

不过,我不太确定字符的含义。

  • GetPixel内部调用LockBits固定内存
  • 因此最好使用 LockBits 一次,然后用完它
  • 总是打电话UnlockBits
  • 使用 unsafe 的直接指针访问也可以为您提供少量性能
  • 此外(在这种情况下)您的 for 循环可以优化(代码方式)以包括您的其他索引。

例子

protected unsafe void DoStuff(string path)
{

   ...

   using (var b = new Bitmap(path))
   {
      var r = new Rectangle(Point.Empty, b.Size);
      var data = b.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); 
      var p = (int*)data.Scan0;

      try
      {
         for (int i = 0; i < 16; i++, Y++)
            for (int j = 0, X = 0; j < 9; j++, X++)
               *(p + X + Y * r.Width) = character[i][j] == 1 ? BG : FG;
      }
      finally
      {
         b.UnlockBits(data);
      }
   }
}

Bitmap.LockBits

Locks a Bitmap into system memory.

Bitmap.UnlockBits

Unlocks this Bitmap from system memory.

unsafe

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.


进一步阅读

Unsafe Code and Pointers

Bitmap.GetPixel

LockBits vs Get Pixel Set Pixel - Performance