我在 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
现在,我正在尝试在 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;
}
用途:
var width = CalcTextWidth("Hello", "Arial", 12);
// returns 42.88
如何用 JS 结果调整 .NET 结果?
要获得相同的结果,您必须:
例如,这段代码应该给你相同的值:
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);
graphics.PageUnit = GraphicsUnit.Point;
SizeF size = graphics.MeasureString(text, font, int.MaxValue, StringFormat.GenericTypographic);
return size.Width;
}