Search code examples
c#.netsystem.drawing

Measure text width and height on .NET6+


Is there any possibility to measure a text width and height on .NET6+ cross-platform? Something like:

var font = new Font("Arial", 16);
var gfx = Graphics.FromImage(new Bitmap(1, 1));
var size = gfx.MeasureString("mystring", font);

Goal:

  • I want to know the text width and height in milimeters
  • My application should target linux

Actual results:

The TextRenderer.MeasureText function is part of System.Windows.Forms which is limitted to -windows.

Another option is Graphics.MeasureString it is part of System.Drawing which is generally available without much dependencies but this function is also flagged as -windows.


Solution

  • Thanks @panagiotis-kanavos! SixLabors.ImageSharp.Drawing is providing such a function and is fully cross-platform compatible:

    var font = SystemFonts.CreateFont("Arial", 10);
    var fontRectangle = TextMeasurer.MeasureAdvance("Foo", new TextOptions(font));