See the question and my original answer on StackOverflow

To get the same result you must:

  • Change the Graphics PageUnit to Point (by default it's Display)
  • Change the GDI+ (System.Drawing) string format to GenericTypographic which is usually better for interoperability with other systems.

So for example this code should give you the same value:

public static double CalcTextWidth(string text, string fontName, float fontSize)
{
    Font font = new(fontName, fontSize);

    using Bitmap bitmap = new(1, 1);
    using Graphics graphics = Graphics.FromImage(bitmap);
    graphics.PageUnit = GraphicsUnit.Point;
    SizeF size = graphics.MeasureString(text, font, int.MaxValue, StringFormat.GenericTypographic);
    return size.Width;
}