0

I am trying to find out the a character's width and height in windows environment using this code:

using(Graphics g = Graphics.FromImage(new Bitmap(800,550)))
{
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        SizeF size = g.MeasureString("0",new Font(FontFamily.GenericMonospace, 10) , new PointF(0, 0), 
            StringFormat.GenericTypographic);
        Console.WriteLine(size.Height);
        Console.WriteLine(size.Width);
}

The output is: Height: 15.104165 Width: 8.001301

I am trying to port this process to cross platform code using SkiaSharp using this code:

using (SKPaint p = new SKPaint
           {
               IsAntialias = true, Typeface = SKTypeface.FromFamilyName("monospace"),
               TextSize = 10
           })
    {
            string text = "0" ;
            SKRect textBounds = SKRect.Empty;
            p.Color = SKColors.Black;
            p.Style = SKPaintStyle.Fill;
            p.MeasureText(text, ref textBounds);
            Console.WriteLine(textBounds.Height);
            Console.WriteLine(textBounds.Width);
    }

This is the height and width of same character in SkiaSharp: Height: 7 Width: 5

Can I get some help regarding this? What am I missing?

Ali Ahmad
  • 23
  • 3
  • Read [this](https://stackoverflow.com/a/36357697/8170844) answer regarding GraphicsUnit. GDI+ defaults to GraphicsUnit.Point (which will depend on your screen's dpi and app's dipAware settings) whereas SkiaSharp defaults to [pixels](https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skpaint.textsize?view=skiasharp-2.88). – Yitz Sep 10 '22 at 22:43
  • @Yitz thank you for the article. Is there any way to make the conversion between Point and Pixel, regardless of DPI settings? – Ali Ahmad Sep 11 '22 at 00:01
  • Not really, points is 1/72 of an inch and you need to know your dpi to find out how many pixels that translates to. You could look at the Horizontal/VericalResolution properties of your Bitmap or DpiX/Y properties of your graphics to see what the default is in your environment, but that text on that bitmap will look different if you ran that program on a different dpi screen. – Yitz Sep 11 '22 at 09:41
  • @AliAhmad you are using generic font families, for me the skia resolves monospace to SegoeUI while GDI resolves it to Courier New. This will more likely yield different measurement. – Maku Dec 04 '22 at 21:53

0 Answers0