Remotion LabRemotion Lab
視覺設計測量與佈局

測量與佈局

在 Remotion 中測量元素尺寸和處理動態佈局。

為什麼要測量?

有時候你需要知道一個元素的實際大小,例如:

  • 根據文字長度調整容器大小
  • 讓動畫精確地移動到元素邊緣
  • 動態排列不同大小的元素

使用 measureText

Remotion 的 measureText() 可以計算文字的寬度和高度:

import { measureText } from "@remotion/layout-utils";
 
const measurement = measureText({
  text: "Hello, Remotion!",
  fontFamily: "Arial",
  fontSize: 72,
  fontWeight: "bold",
});
 
console.log(measurement.width);  // 文字寬度(像素)
console.log(measurement.height); // 文字高度(像素)

安裝:

npm install @remotion/layout-utils

實際用途:文字外框

根據文字大小自動調整背景框的尺寸:

import { measureText } from "@remotion/layout-utils";
 
export const TextBox: React.FC<{ text: string }> = ({ text }) => {
  const { width } = measureText({
    text,
    fontFamily: "Arial",
    fontSize: 48,
    fontWeight: "bold",
  });
 
  const padding = 24;
 
  return (
    <div style={{ position: "relative", display: "inline-block" }}>
      <div
        style={{
          position: "absolute",
          width: width + padding * 2,
          height: 48 + padding * 2,
          backgroundColor: "rgba(0,0,0,0.7)",
          borderRadius: 12,
          top: -padding,
          left: -padding,
        }}
      />
      <span style={{ fontSize: 48, fontWeight: "bold", color: "white", position: "relative" }}>
        {text}
      </span>
    </div>
  );
};

fillTextBox

自動計算能放入容器的最大字體大小:

import { fillTextBox } from "@remotion/layout-utils";
 
const { fontSize } = fillTextBox({
  maxBoxWidth: 800,
  maxLines: 2,
  text: "這是一段很長的文字,需要自動調整字體大小以適應容器寬度",
  fontFamily: "Arial",
  fontWeight: "bold",
});
 
// fontSize 會是能讓文字在 2 行內、800px 寬度內顯示的最大值

小結

  • measureText() 計算文字的精確尺寸
  • 可用於自動調整容器、對齊元素
  • fillTextBox() 自動計算最大字體大小
  • 安裝 @remotion/layout-utils 使用這些工具