在.net framework中,绘制图形一般是使用Graphics.DrawImage方法,但是这个方法在许多时候有明显的缺陷。

以上是一张图的两种显示效果。左侧为windows自身的缩略图显示效果,右侧为调用DrawImage方法所显示的效果。源图为tiff格式,幅面大小为3185*2276,300*300dpi,图形文件大小52.4KB。可以看到两种显示效果有明显的区别,这是由于DrawImage在处理图形的高比例缩小时采用了默认算法,导致了图形显示的严重失真。
更为严重的缺陷是,DrawImage函数对于更大幅面的图像绘制几乎完全不能胜任,测试中使用了一个幅面为13290*9600,400*400dpi,大小为2.5MB的一个tiff文件,DrawImage函数一运行一下子就使得我的本本虚拟内存全部耗完,整个系统陷入没有响应的状态!
基于以上原因,在绘制大型图像时,已不能再使用.net framework提供的DrawImage方法。在最近我做的一个程序中,便重新开发了一个C++的动态链接库来完成大型图像的绘制,显示的效果和速度均得到极佳的体现!
C++绘制函数原型:
1
extern "C" void HighSpeedDraw(HDC hDC, int srcLeft, int srcTop, int srcRight, int srcBottom,
2
int dstLeft, int dstTop, int dstRight, int dstBottom)
3
{
4
CDC* pDC = CDC::FromHandle(hDC);
5
CRect srcRect(srcLeft, srcTop, srcRight, srcBottom);
6
CRect dstRect(dstLeft, dstTop, dstRight, dstBottom);
7
pDrawEngine->Draw(pDC, dstRect, srcRect);
8
}
extern "C" void HighSpeedDraw(HDC hDC, int srcLeft, int srcTop, int srcRight, int srcBottom,2
int dstLeft, int dstTop, int dstRight, int dstBottom)3
{4
CDC* pDC = CDC::FromHandle(hDC);5
CRect srcRect(srcLeft, srcTop, srcRight, srcBottom);6
CRect dstRect(dstLeft, dstTop, dstRight, dstBottom);7
pDrawEngine->Draw(pDC, dstRect, srcRect);8
}在C#中的包装:
1
[DllImport("HSDraw.dll")]
2
private extern static void HighSpeedDraw(IntPtr hDC, int srcLeft, int srcTop, int srcRight, int srcBottom,
3
int dstLeft, int dstTop, int dstRight, int dstBottom)
[DllImport("HSDraw.dll")]2
private extern static void HighSpeedDraw(IntPtr hDC, int srcLeft, int srcTop, int srcRight, int srcBottom,3
int dstLeft, int dstTop, int dstRight, int dstBottom)OK,在Paint函数中就可以这样调用了:
1
try
2
{
3
checked
4
{
5
IntPtr hDC = e.Graphics.GetHdc();
6
HighSpeedDraw(hDC, sourceRect.Left, sourceRect.Top, sourceRect.Right, sourceRect.Bottom,
7
targetRect.Left, targetRect.Top, targetRect.Right, targetRect.Bottom);
8
e.Graphics.ReleaseHdc(hDC);
9
}
10
}
11
catch (Exception ex)
12
{
13
graphics.DrawString(ex.ToString(), new Font("Arial", 8), Brushes.Red, new PointF(0, 0));
14
}
try2
{3
checked4
{5
IntPtr hDC = e.Graphics.GetHdc();6
HighSpeedDraw(hDC, sourceRect.Left, sourceRect.Top, sourceRect.Right, sourceRect.Bottom,7
targetRect.Left, targetRect.Top, targetRect.Right, targetRect.Bottom);8
e.Graphics.ReleaseHdc(hDC);9
}10
}11
catch (Exception ex)12
{13
graphics.DrawString(ex.ToString(), new Font("Arial", 8), Brushes.Red, new PointF(0, 0));14
}以下是使用C++绘制算法看到的效果:

可以看到,新的算法绘制的效果非常好。此外,原先使用DrawImage导致系统无法响应的tiff文件,现在绘制所耗时间在1秒以内,图像绘制所消耗的内存也降至20M以下,效果得到了明显的提高。



浙公网安备 33010602011771号