I have two Methods to return width of string:
The first method is using System.Drawing
:
public static float GetTextWidth(string fontFace, float fontSize, string text)
{
var fontx = new System.Drawing.Font(fontFace, fontSize);
//Using a Bitmap object for frame of reference in order to get to a Graphics object
using Bitmap b = new(1, 1);
//Graphics object allows string measurement
using Graphics g = Graphics.FromImage(b);
//change the units to Point
g.PageUnit = GraphicsUnit.Point;
retrun g.MeasureString(text, fontx).Width;
}
The second method is using SixLabors.Fonts
:
public static float GetTextWidth(string fontFace, float fontSize, string text)
{
var font = SixLabors.Fonts.SystemFonts.CreateFont(fontFace, fontSize);
var sizeF = TextMeasurer.Measure(text, new TextOptions(font));
return sizeF.Width;
}
If you compare between the images you can see that the text is going down in the second method that used SixLabors
library and this is wrong. In the debug mode I see that the deference between the width in both are always 10
.
My question:
because of System.Drawing.Common only supported on Windows, I have to switch to SixLabors
but I don't understand why the width is always '10' more when I use SixLabors
. Can anyone explain to me why and how can I solve it?