I would get the width (so a dimension) of a string in a box. I need to know the width of \hphantom{some text}, in order to use it into a tikz picture, for example as \draw (0,0)--(\mylen,0); that represents a line with the same width of the string some text.

  • 1
    \settowidth{\mylen}{some text}, assuming you already have \newlength{\mylen} – egreg Jul 13 '13 at 15:41
  • @egreg I need more hint: I would get the width of the chapter title, so I set \newlength{\Titolo} and then \settowidth{\Titolo}{#1}, where #1 is the argument of \chapter so its title. But doing so the width seems to be zero – Martino Jul 13 '13 at 15:51
  • We need more hints from you too. What precisely do you want to do? Anyway, you need to also set the font used for the chapter title. – egreg Jul 13 '13 at 15:53
  • In general, I want to know how is the width (in pt) of a string. This would allows me to use the dimension I need into tikz environment, for example to create a line that runs from x0 to x0+\thewidth. But actually I don't know \thewidth, and I cannot put x_0+\hphantom{string}. – Martino Jul 13 '13 at 16:02
  • 2
    Then \settowidth{\mylen}{string} will do; however you have to do \settowidth outside the tikzpicture, or in a \pgfextra instruction. But a real example of what you're trying to achieve will help. – egreg Jul 13 '13 at 16:06

If you only have regular text in the box then TikZ can measure it too, which is what you are trying to do manually anyways. It just uses its own temporary box to measure. But \textbf etc. stuff is not so easy to use. So use it with caution.

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

Oh and height works too.

enter image description here

  • I think this is where this solution fails for the OP's intent of measuring the width of a chapter title, where font changing commands are probably needed. Of course this is a shot in the dark and is based only on an OP's comment. – egreg Jul 13 '13 at 18:17
  • @egreg Oops, I didn't read that part. Let me try to find a simple example. – percusse Jul 13 '13 at 18:19

Declare a new box at preamble (for example). Put your object inside the box. And you can access the box width and height.

\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.

The calc package provides the \widthof{some text} command with which you can measure the width of a particular string (here: some text). You can use it like you would use any other length in LaTeX, e.g. 2cm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.