Search code examples
c#drawstring

Graphics.DrawString doesn't draw last SPACE chars?


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


Solution

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