【问题标题】:Justifying text using DrawString in C#在 C# 中使用 DrawString 对齐文本
【发布时间】:2016-01-21 17:26:22
【问题描述】:

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

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

感谢您的帮助!

【问题讨论】:

    标签: c# system.drawing


    【解决方案1】:

    我找到了:)

    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.
    }
    

    【讨论】:

      【解决方案2】:

      没有内置的方法可以做到这一点。此线程中提到了一些解决方法:

      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);
      

      不确定这可以如何集成到您现有的模型中(因为我假设您绘制的不仅仅是文本),但它可能是您唯一的选择。

      【讨论】:

        猜你喜欢
        • 2012-06-09
        • 1970-01-01
        • 2020-09-06
        • 2016-07-28
        • 2020-07-10
        • 2014-09-05
        • 2014-10-26
        • 2017-08-11
        相关资源
        最近更新 更多