c#中使用DrawString对齐文本
本文关键字:对齐 文本 DrawString | 更新日期: 2023-09-27 18:09:26
我正在System.Drawing.Graphics
对象上绘制文本。我使用DrawString
方法,文本字符串,一个Font
,一个Brush
,一个边界RectangleF
和一个StringFormat
作为参数。
查看StringFormat
,我发现我可以将其Alignment
属性设置为Near
, Center
或Far
。然而,我还没有找到一种方法来设置它为正当的。我怎样才能做到这一点呢?
谢谢你的帮助!
I FOUND IT:)
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.
}
没有内置的方法可以这样做。在这个线程中提到了一些变通方法:
http://social.msdn.microsoft.com/forums/zh/winforms/thread/aebc7ac3 - 4732 - 4175 - a95e - 623 fda65140e
他们建议使用覆盖的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);
不确定这可以集成到您现有的模型中有多好(因为我假设您绘制的不仅仅是文本),但它可能是您唯一的选择。