textUtils.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. // sheep/utils/textUtils.js
  2. export function measureTextWidth(text, fontSize = 14, fontFamily = 'sans-serif') {
  3. // 钉钉小程序没有 uni.createCanvasContext 方法
  4. if (typeof uni === 'undefined' || typeof uni.createCanvasContext !== 'function') {
  5. return estimateTextWidth(text, fontSize);
  6. }
  7. try {
  8. const ctx = uni.createCanvasContext('tempCanvasForText');
  9. ctx.setFontSize(fontSize);
  10. ctx.font = `${fontSize}px ${fontFamily}`;
  11. const metrics = ctx.measureText(text);
  12. return metrics.width;
  13. } catch (e) {
  14. // 某些平台可能不支持 measureText,降级使用估算
  15. return estimateTextWidth(text, fontSize);
  16. }
  17. }
  18. // 简单估算中文和英文字符宽度
  19. function estimateTextWidth(text, fontSize = 14) {
  20. let width = 0;
  21. for (let i = 0; i < text.length; i++) {
  22. const charCode = text.charCodeAt(i);
  23. if (charCode >= 0x4e00 && charCode <= 0x9fff) {
  24. // 中文字符
  25. width += fontSize;
  26. } else {
  27. // 英文字符
  28. width += fontSize * 0.5;
  29. }
  30. }
  31. return width;
  32. }