测量包含中英文等多种字符的文本宽度是许多应用场景中的常见需求,特别是在UI布局、打印排版或图形绘制时。以下是几种精确测量文本宽度的方法:
function getTextWidth(text, font) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = font || getComputedStyle(document.body).font;
return context.measureText(text).width;
}
// 使用示例
const width = getTextWidth("你好Hello", "14px Arial");
console.log(width);
function getTextWidth(text, font) {
const span = document.createElement('span');
span.style.visibility = 'hidden';
span.style.whiteSpace = 'nowrap';
span.style.font = font || getComputedStyle(document.body).font;
span.textContent = text;
document.body.appendChild(span);
const width = span.offsetWidth;
document.body.removeChild(span);
return width;
}
const { createCanvas } = require('canvas');
function getTextWidth(text, font = '14px Arial') {
const canvas = createCanvas(200, 200);
const ctx = canvas.getContext('2d');
ctx.font = font;
return ctx.measureText(text).width;
}
Paint paint = new Paint();
paint.setTextSize(textSize);
float width = paint.measureText(text);
let text = "你好Hello" as NSString
let size = text.size(withAttributes: [.font: UIFont.systemFont(ofSize: 14)])
let width = size.width
对于更复杂的文本布局需求(如换行、多段落等),可以使用更专业的库:
选择哪种方法取决于您的具体应用场景和性能需求。