9

I need to know the height of a TikZ node and store it in a length so it can later be used by other commands and reference this exact dynamic length.

So here is an MWE that illustrates what I want to do, but of course this is not how \totalheightof works, it measures the height of the text, but I want to get the height of the node:

\documentclass{article}

\newlength{\heightOfMyNode}
\usepackage{tikz,calc}


\begin{document}
\begin{tikzpicture}
\node(mynode)[text width=3cm]{This is a node that varies in height and I need to know the hieght and store it in a length};
\end{tikzpicture}
\setlength{\heightOfMyNode}{\totalheightof{node.height}}

And here I want to use the length for a \rule{\heightOfMyNode}{2pt}
\end{document}

Looking forward to your suggestions, especially direct TikZ/PGF solutions that I overlooked, maybe with \veclen?

1
  • 1
    tcolorbox (section 12.9) includes \tcbsetmacrotowidthofnode and tcbsetmacroheightofnode to store these values inside a macro, but I don't know how to make them to survive outside the tikzpicture.
    – Ignasi
    Jul 20, 2020 at 11:09

1 Answer 1

11

Well, I suppose you just want to know the width and height of box containing a node that may be transformed. Then it is easy to calculate the width and height of the bounding box.

\documentclass[tikz, border=1cm]{standalone}
\usetikzlibrary{fit, calc}
\usepackage{xparse}
\makeatletter
\NewDocumentCommand {\getnodedimen} {O{\nodewidth} O{\nodeheight} m} {
  \begin{pgfinterruptboundingbox}
  \begin{scope}[local bounding box=bb@temp]
    \node[inner sep=0pt, fit=(#3)] {};
  \end{scope}
  \path ($([email protected] east)-([email protected] west)$);
  \end{pgfinterruptboundingbox}
  \pgfgetlastxy{#1}{#2}
}
\makeatother

\begin{document}
\begin{tikzpicture}
  \node(mynode)[text width=3cm, draw=red]{This is a node that varies in height and I need to know the hieght and store it in a length};
  \getnodedimen{mynode}
  \node[draw, minimum height=\nodeheight, minimum width=\nodewidth] at (4, 0) {};
\end{tikzpicture}
\end{document}

enter image description here

5
  • Thanks @ZhiyuanLck, that looks like a promising solution, however on my machine your code results in: ! Dimension too large. <to be read again> \pgf@y l.17 \getnodedimen{mynode} I can't work with sizes bigger than about 19 feet. Continue and I'll use the largest value I can.
    – TobiBS
    Jul 20, 2020 at 9:17
  • +1 a clever solution!
    – Black Mild
    Jul 20, 2020 at 9:23
  • 1
    @TobiBS This error ocurr in texlive 2019 or lower. I'll try to fix it.
    – ZhiyuanLck
    Jul 20, 2020 at 9:23
  • I have changed my answer @TobiBS
    – ZhiyuanLck
    Jul 20, 2020 at 10:02
  • Just got the same error using TL2022, when measuring a node being exactly 34.40729pt high and about 216mm wide (as I measured by other means). Aug 27, 2022 at 22:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .