I have this code in JS:
function getTextWidth(text, font) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = font;
return context.measureText(text).width;
}
const myWidth = getTextWidth("Hello", "12px Arial");
// returns 27.345703125
Now, I'm trying to implement the same in C#.
public static double CalcTextWidth(string text, string fontName, float fontSize)
{
Font font = new (fontName, fontSize);
using Bitmap bitmap = new(1, 1);
using Graphics graphics = Graphics.FromImage(bitmap);
SizeF size = graphics.MeasureString(text, font);
return size.Width;
}
Usage:
var width = CalcTextWidth("Hello", "Arial", 12);
// returns 42.88
How can I adjust the .NET result with JS result?
To get the same result you must:
So for example this code should give you the same value: