在C#中使用DrawString对文本进行对齐

我在System.Drawing.Graphics对象上绘制文本。 我正在使用DrawString方法,文本字符串, FontBrush ,边界RectangleFStringFormat作为参数。

看看StringFormat ,我发现我可以将它的Alignment属性设置为NearCenterFar 。 但是我还没有找到将其设置为Justified的方法。 我怎样才能做到这一点?

谢谢您的帮助!

没有内置的方法来做到这一点。 在这个post中提到了一些解决方法:

http://social.msdn.microsoft.com/Forums/zh/winforms/thread/aebc7ac3-4732-4175-a95e-623fda65140e

他们建议使用重写的RichTextBox ,覆盖SelectionAlignment属性(请参阅此页面了解如何 )并将其设置为Justify

覆盖的内容围绕这个pInvoke调用:

 PARAFORMAT fmt = new PARAFORMAT(); fmt.cbSize = Marshal.SizeOf(fmt); fmt.dwMask = PFM_ALIGNMENT; fmt.wAlignment = (short)value; SendMessage(new HandleRef(this, Handle), // "this" is the RichTextBox EM_SETPARAFORMAT, SCF_SELECTION, ref fmt); 

不确定这可以集成到现有模型中的程度(因为我假设你的绘图比文本更多),但它可能是你唯一的选择。

我找到了 :)

http://csharphelper.com/blog/2014/10/fully-justify-a-line-of-text-in-c/

简而言之 – 当您知道整个段落的给定宽度时,您可以在每个单独的行中对齐文本:

 float extra_space = rect.Width - total_width; // where total_width is the sum of all measured width for each word int num_spaces = words.Length - 1; // where words is the array of all words in a line if (words.Length > 1) extra_space /= num_spaces; // now extra_space has width (in px) for each space between words 

其余的很直观:

 float x = rect.Left; float y = rect.Top; for (int i = 0; i < words.Length; i++) { gr.DrawString(words[i], font, brush, x, y); x += word_width[i] + extra_space; // move right to draw the next word. }