3

The string is "Hello World " with 10 SPACE chars in the end, but Graphics.DrawString in Right Alignment omits all of SPACE chars, it just draws "Hello World" only.

protected override void OnPaint(PaintEventArgs e)
    {            
        Rectangle rct = new Rectangle(20, 100, 200, 20);
        e.Graphics.DrawRectangle(new Pen(Color.Lime), rct);            
        e.Graphics.DrawString("Hello World          ", Font, new SolidBrush(SystemColors.ControlText), rct, new StringFormat() { Alignment = StringAlignment.Far});                                                      

        base.OnPaint(e);
    }

enter image description here

qtg
  • 125
  • 1
  • 11
  • 1
    Thanks. The flag works. You save me many hours. Can you do me a favor to make this as an Answer? – qtg Dec 02 '22 at 12:59

1 Answers1

1

To include the Trailing Spaces when drawing strings with Gdi+ Graphics.DrawString method, pass a StringFormat to a proper overload and add or append (|=) the StringFormatFlags.MeasureTrailingSpaces value to the StringFormat.FormatFlags property.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Rectangle rct = new Rectangle(20, 100, 200, 20);
    string s = "Hello World          ";

    using (var sf = new StringFormat(StringFormat.GenericTypographic))
    {
        sf.Alignment = StringAlignment.Far;
        sf.LineAlignment = StringAlignment.Center;
        sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

        e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
        e.Graphics.DrawString(s, Font, SystemBrushes.ControlText, rct, sf);
    }

    e.Graphics.DrawRectangle(Pens.Lime, rct);
}

Consider using the Gdi TextRenderer class to draw strings over controls unless you encounter problems like drawing on transparent backgrounds.

The previous code could have been written like:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Rectangle rct = new Rectangle(20, 100, 200, 20);
    string s = "Hello World          ";

    TextRenderer.DrawText(e.Graphics, s, Font, rct, SystemColors.ControlText,
        TextFormatFlags.Right |
        TextFormatFlags.VerticalCenter);

    e.Graphics.DrawRectangle(Pens.Lime, rct);
}
dr.null
  • 4,032
  • 3
  • 9
  • 12
  • 1
    Though this answer, I not only resolved my particular problem but also learned proper coding style. I have being confused by MS doc about StringFormatFlags.MeasureTrailingSpaces in English. If the doc said "... the trailing SPACE chars at the end of ..." then I could understand better. – qtg Dec 03 '22 at 02:28