dennis
dennis

Reputation: 316

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:

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.

Upvotes: 0

Views: 98

Answers (1)

dennis
dennis

Reputation: 316

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

Upvotes: 0

Related Questions