C# GDI+ 不能绘制带空格的文本

C# GDI+ can't draw text with spaces

我有一些代码:

string text = "Some text\t with tabs\t  here!";
string spaces = "";
for (int i = 0; i < 4; i++)
{
    spaces += " ";
}

text = text.Replace(@"\t", spaces);

我用四个 space 替换所有标签,然后尝试绘制文本:

graphics.DrawString(text, font, new SolidBrush(Color.Black), offsetX, offsetY);

但是文字之间只有一个space。其他 space 被删除。 如何使用所有 space 绘制文本?

您的字符串或其中的 none 必须是 逐字字符串 。逐字字符串(即@"string")表示,在到达下一个引号字符之前不对字符应用任何解释

因此试试这个:

string text = "Some text\t with tabs\t  here!";
...
text = text.Replace("\t", spaces);

或者这样:

string text = @"Some text\t with tabs\t  here!";
...
text = text.Replace(@"\t", spaces);

问题出在你的字体上,有些字体有单声道spaced(所有字母表都相同 space,包括 space)而其他字体没有(每个字母表都不同 space 例如 "i" 比 "M" 少 space)。请将您的字体更改为单声道spaced 字体。

您看到您的文本似乎只有一个 space,因为非单声道spaced 字体中的 space 比单声道spaced 字体短。

您可以阅读有关 monospaced fonts in Wikipedia 的更多信息。

改用TextRenderer.DrawText。这也是自 .NET 2.0 以来 Windows.Forms 使用的内容,除非 UseCompatibleTextRendering 已打开。

TextRenderer.DrawText(graphics, text, font,
    new Point(offsetX, offsetY), Color.Black, TextFormatFlags.ExpandTabs);