Search code examples
c#winformsgdi+

Graphics.DrawString weird abnormal kerning


I am developing a label designing program and I have encountered a very weird issue that I cannot find an answer to anywhere on the internet.

The basic explanation is that when the layoutRectangle property of DrawString() is set to anything slightly higher than the size of the text length, The kerning seems to just turn off. It's best visible with a combination of characters 'Te'.

Correct Kerning with 'layoutRectangle' just enough to fit the text:
1

Wrong kerning with 'layoutRectangle' larger than required to fit the text:
2

You probably can spot the 'e' in the second image being drawn much further than in the first image. I have tried that on a new project, the same thing happens. You can observe the same behaviour even when not specifying the layoutRectangle at all.

Here is the line of code that draws the string:

canvasGraphics.Graphics.DrawString(
    _displayText.FormattedTextValue,
    new Font(FontName, (float)((drawFontSizeToUse / 72d) * Canvas.RenderDPI), fontStyle, GraphicsUnit.Pixel),
    Brushes.Black,
    (Rectangle)new RectangleD(ScreenBounds.X, ScreenBounds.Y, ScreenBounds.Width, ScreenBounds.Height),
    stringFormat
);

stringFormat just changes the alignment depending on the setting.

Does anyone know how to fix this issue? Thank you!

I have tried manipulating different StringFormat, TextRenderingHint and any Font options etc. (Although there might be some that I do not know of.)

I cannot use 'TextRenderer' as it cannot be used for printing.


Solution

  • I just wanted to make sure this question is finished and is going to help someone down the line.

    I want to thank @Ian Boyd and @dr.null for their answers, and they are really helpful for the future. I suggest anyone that is facing text drawing issues look at their answers and try to adapt their responses.

    For my purposes, as I really do not want to change the way things are ran now, and I need printing functionality, I found a very simple fix to this issue and that is:

    Add "\n" to the end of the string parameter passed onto the Graphics.DrawString. It's a ridiculous and an easy fix, but it works!