Skip to main content

调试字体测量错误

当你发现从measureText()fillTextBox()fitText()获取的测量值不准确并且导致布局问题时,请按照本页的调试说明进行操作。

🌐 When you find that the measurements that you are getting from measureText(), fillTextBox() or fitText() are off and are causing layout issues, follow the debugging instructions on this page.

在 Remotion Studio 中打开你的项目,并选择你发现问题的合成。
2
将缩放设置为 100%,以排除因缩放比例引起的任何问题。
3
在组件底部渲染一个 <div>,其中包含字符串和你传递给 measureText() 的所有属性。

Sample markup
import {AbsoluteFill} from 'remotion'; const MyComp: React.FC = () => { const fontSize = 100; const fontWeight = 'bold'; const fontFamily = 'Roboto'; const text = 'Hello World '; const letterSpacing = undefined; const fontVariantNumeric = undefined; const textTransform = undefined; return ( <AbsoluteFill> <div id="remotion-measurer" style={{ display: 'inline-block', whiteSpace: 'pre', fontSize, fontWeight, fontFamily, letterSpacing, fontVariantNumeric, textTransform, }} > {text} </div> </AbsoluteFill> ); };

打开 Chrome 开发者工具,并在“元素”标签中选择 <div id="remotion-measurer"> 节点。
5
该节点会高亮显示,你可以看到它的尺寸。检查是否有任何意外的偏差。
6
使用“计算”标签,查看所有可能影响布局的属性,并将其与在你的组合中出现问题的节点进行比较。如果尺寸不同,至少会有一个计算属性的值不同。
7
调整你的标记,使其具有与你的组合中节点相同的计算属性。

记住

🌐 Remember

  • 文本使用 whiteSpace: "pre" 进行测量,包括空白字符。
    • 如果你不想测量空白,请在你的字符串上调用 .trim()
    • 确保 whiteSpace: "pre" 应用于整个容器,而不仅仅是单个单词。
    • 确保在拆分文本时不要删除任何空格,同时在测量时保留它们。
  • 在调用 measureText() 时确保字体已加载。
    • 使用 validateFontIsLoaded 选项以确保字体被加载。
  • 可能会应用外部样式。查看是否有 CSS 重置、TailwindCSS 样式表或其他外部资源影响了你的布局。
    • 如果是这种情况,你可以在 Chrome 开发者工具的计算属性面板中看到它。
  • 不要在你的文本中使用 paddingborder。使用 outline 替代 border
  • 不要将字体大小与 useCurrentScale() 相乘。这会导致布局混乱。

另请参阅

🌐 See also

你也可以查看 measureText() 的源代码,将其粘贴并在你的项目中自定义,以帮助调试。

🌐 You can also check out the source code of measureText(), paste and customize it in your project to aid debugging.