1

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 result from this method enter image description here

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

The result from this method : enter image description here

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?

Nb777
  • 1,658
  • 8
  • 27
  • Text will only ever wrap when a wrapping length is not set when a mandatory line break exists in your input text. Also your DPI will be different. – James South Jul 25 '22 at 07:24
  • @JamesSouth, thanks for you answer, I didn't understand the relation between your comment and **My question** ! – Nb777 Jul 25 '22 at 07:31
  • _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_ I'm telling you why the text is wrapped. _I don't understand why the width is always '10' more when I use SixLabors._ Text measurements are measured in pixels. If the DPI is different then the pixel size will be different. – James South Jul 26 '22 at 07:37

0 Answers0