[英]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);
我用四個空格替換所有選項卡,然后嘗試繪制文本:
graphics.DrawString(text, font, new SolidBrush(Color.Black), offsetX, offsetY);
但是文本在單詞之間僅留出一個空格。 並刪除其他空格。 如何用所有空格繪制文本?
您的兩個字符串或者都不是逐字字符串 。 逐字字符串(即@“ 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);
請改用TextRenderer.DrawText 。 從.NET 2.0開始,除非啟用UseCompatibleTextRendering,否則Windows.Forms也將使用此功能。
TextRenderer.DrawText(graphics, text, font,
new Point(offsetX, offsetY), Color.Black, TextFormatFlags.ExpandTabs);
問題是您的字體,某些字體是等距的(所有字母都有相同的空格,包括空格),而其他字體則沒有(每個字母不同的空格,例如“ i”的空格要小於“ M”)。 請將其更改為等寬字體。
您會發現您的文本似乎只有一個空格,因為非等寬字體的空格比等距字體的空格要短。
您可以在Wikipedia中閱讀有關等寬字體的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.