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