在C#中使用DrawString对文本进行对齐
我在System.Drawing.Graphics
对象上绘制文本。 我正在使用DrawString
方法,文本字符串, Font
, Brush
,边界RectangleF
和StringFormat
作为参数。
看看StringFormat
,我发现我可以将它的Alignment
属性设置为Near
, Center
或Far
。 但是我还没有找到将其设置为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. }