[Tex/LaTex] \widthof within tikzpicture

calculationstikz-pgfwidth

In this minimal example

\documentclass{scrartcl} 

\usepackage{calc} 
\usepackage{tikz} 

\newlength{\TestLength} 

\begin{document} 

    \setlength{\TestLength}{\widthof{\tikz \node {bla};}} 
    \showthe\TestLength% MEASUREMENT 1 

    \begin{tikzpicture} 
            \setlength{\TestLength}{\widthof{\node {bla};}} 
            \showthe\TestLength% MEASUREMENT 2 
    \end{tikzpicture} 

\end{document}

\TestLength is calculated correctly in the first time (MEASUREMENT 1), but too small in the second time (MEASUREMENT 2). I'd like to calculate it within a tikzpicture environment, so that I'm fixed to the second way of calculation. is there any workaround?

Thanks a lot for any kind of comments or ideas.

Best Answer

If you want to measure the size of a node that has already been typeset and named, you can use the following code:

\documentclass{article}
\usepackage{tikz}

\begin{document}

% \getwidthofnode will measure the width of the node given as its second
% parameter and store it into the first parameter.
\makeatletter
\newcommand\getwidthofnode[2]{%
    \pgfextractx{#1}{\pgfpointanchor{#2}{east}}%
    \pgfextractx{\pgf@xa}{\pgfpointanchor{#2}{west}}% \pgf@xa is a length defined by PGF for temporary storage. No need to create a new temporary length.
    \addtolength{#1}{-\pgf@xa}%
}
\makeatother

\newlength\TestLength

\begin{tikzpicture}
    \node (mynode) {bla};
    \getwidthofnode{\TestLength}{mynode}
    \showthe\TestLength
\end{tikzpicture}

\end{document}