在C#中使用DrawString对齐文本

6
我正在使用 System.Drawing.Graphics 对象绘制文本。我正在使用 DrawString 方法,将文本字符串、FontBrush、边界 RectangleFStringFormat 作为参数。
在研究 StringFormat 时,我发现可以将其 Alignment 属性设置为 NearCenterFar。然而,我没有找到将其设置为对齐的方法。如何实现呢?
感谢您的帮助!
2个回答

3
我找到了它 :)
简而言之,当您知道整个段落的给定宽度时,可以在每行中对文本进行对齐: 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.
}

1

没有内置的方法来实现它。这个线程中提到了一些解决方法:

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

他们建议使用重写的 RichTextBox,覆盖 SelectionAlignment 属性(请参见 this page for how)并将其设置为 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);

不确定这个能否很好地集成到您现有的模型中(因为我假设您正在绘制更多的内容而不仅仅是文本),但这可能是您唯一的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接