在 .net framework 中 graphics.drawstring 方法提供了基本的文本绘制功能。然而,这个方法本身缺乏对字符格式的控制能力,例如不支持多数文本处理器支持的字符间距(大概微软认为不会有人编写基于 .net 的文本处理器)。这个问题最简单的解决方法是将整个字符串“化整为零”,一个字符一个字符的按照指定间距画出来。然而这样做会产生大量的临时字符串,而且有巨大的 pinvoke 代价。那有没有其他的方法呢?答案是肯定的——gdi+ 底层提供了 gdipdrawdriverstring 方法,允许我们对单个字符的输出位置进行控制。遗憾的是也许因为这个方法太底层了,所以在 .net framework 中并没有针对它的封装。(顺便说一下,office 从 office xp 开始就使用 gdi+ 作为绘图引擎,象 visio 中的文本绘制就使用了 gdipdrawdriverstring)
下面是对 gdipdrawdriverstring 的简单封装(gdiplusmethods.cs):
using system;
using system.drawing.drawing2d;
using system.reflection;
using system.runtime.interopservices;
namespace system.drawing
{
/// <summary>
/// summary description for gdiplusmethods.
/// </summary>
public class gdiplusmethods
{
private gdiplusmethods() { }
private enum driverstringoptions
{
cmaplookup = 1,
vertical = 2,
advance = 4,
limitsubpixel = 8,
}
public static void drawdriverstring(graphics graphics, string text,
font font, brush brush, pointf[] positions)
{
drawdriverstring(graphics, text, font, brush, positions, null);
}
public static void drawdriverstring(graphics graphics, string text,
font font, brush brush, pointf[] positions, matrix matrix)
{
if (graphics == null)
throw new argumentnullexception("graphics");
if (text == null)
throw new argumentnullexception("text");
if (font == null)
throw new argumentnullexception("font");
if (brush == null)
throw new argumentnullexception("brush");
if (positions == null)
throw new argumentnullexception("positions");
// get hgraphics
fieldinfo field = typeof(graphics).getfield("nativegraphics",
bindingflags.instance | bindingflags.nonpublic);
intptr hgraphics = (intptr)field.getvalue(graphics);
// get hfont
field = typeof(font).getfield("nativefont",
bindingflags.instance | bindingflags.nonpublic);
intptr hfont = (intptr)field.getvalue(font);
// get hbrush