I'm drawing text to an off-screen bitmap. Unfortunately, the text is not properly left aligned (see image below). The text should touch the left margin (blue line) but is off by a few pixel. The distance grows with the text size.

How can I get rid of this distance?
I'm using .NET Framework 4.6.1. But it seems to more a general GDI+ issue that I don't understand.
Code used to generate the sample:
using System.Drawing;
using System.Drawing.Imaging;
namespace LeftAlignment
{
class Program
{
static void Main(string[] args)
{
const int LeftMargin = 10;
// create off-screen bitmap
using (Bitmap bitmap = new Bitmap(300, 100))
{
// create graphics context
using (Graphics graphics = Graphics.FromImage(bitmap))
{
// clear bitmap
graphics.FillRectangle(Brushes.White, 0, 0, bitmap.Width, bitmap.Height);
// draw border and left margin
graphics.DrawRectangle(Pens.Gray, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
graphics.DrawLine(Pens.Blue, LeftMargin, 8, LeftMargin, 92);
// draw string at 24 pt
Font font = new Font("Arial", 24);
graphics.DrawString("Cool water", font, Brushes.Black, LeftMargin, 8);
// draw string at 36 pt
font = new Font("Arial", 36);
graphics.DrawString("Cool water", font, Brushes.Black, LeftMargin, 44);
}
// save result as PNG
bitmap.Save("alignment.png", ImageFormat.Png);
}
}
}
}
The story goes that Microsoft added the padding in GDI+ to make it easier to implement controls. The old GDI didn't have that problem.
When Microsoft realized it was a mistake, they added the TextRenderer class that bypasses GDI+ and uses the better GDI implementation.
The padding is supposedly 1/6 em on the left and 1/4 em on the right hand side.
You have two options:
Use TextRenderer.DrawText. However, it's part of Windows Forms. So it won't be available neither in .NET Standard nor .NET Core.
Use Graphics.DrawString with the magic option StringFormat.GenericTypographic. It magically removes the padding.
Also see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With