取得盒子的寬度(以 pt 為單位)

取得盒子的寬度(以 pt 為單位)

我會得到盒子中字串的寬度(即尺寸)。我需要知道 , 的寬度\hphantom{some text},以便將其用於 tikz 圖片,例如,\draw (0,0)--(\mylen,0);它代表與字串 相同寬度的線some text

答案1

如果框中只有常規文本,那麼 TikZ 也可以測量它,這正是您嘗試手動執行的操作。它只是用自己的臨時盒子來測量。但\textbf等等東西並不是那麼好用。因此請謹慎使用。

\begin{tikzpicture}
\pgfmathsetmacro\mylen{width("some text")}
\node[anchor=west,inner sep=0] {some text};
\draw[red,thick] (0,0) -- (\mylen pt,0);
\end{tikzpicture}

哦,height也有效。

在此輸入影像描述

答案2

在序言中聲明一個新框(例如)。將您的物體放入盒子內。您可以存取框的寬度和高度。

\newsavebox\IBox% declare a box
\savebox\IBox{some text}% put an object inside the box
% other codes...
\draw (0,0) -- (\wd\IBox,\ht\IBox) node {\usebox\IBox};% access the width, height of the box and make use of the box.

答案3

calc套件提供了\widthof{some text}可以測量特定字串寬度的命令(此處:一些文字)。您可以像在 LaTeX 中使用任何其他長度一樣使用它,例如2cm

相關內容