3

When the node is too big, we tend to switch the arrows to ->| 2cm |<-. Is there a smart way to do this without drawing two separate lines?


We can see from the image [>= stealth, |<->|] the arrow tips barely shows since 19.02 mm takes up the whole line segment.

enter image description here

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[>= stealth, |<->|] (0, -0.3cm) -- ++(1cm, 0)
  node[pos = 0.5, fill = white, font = \tiny, inner sep = 0] {$19.02$ mm};
\end{tikzpicture}
\end{document}
3

Just the basics, a lot needs to be parametrized to make a decent solution but the following shows one way using a decoration and the \pgfnodepositionlater trick. As I've used the node contents key, this requires the latest PGF release:

\documentclass[tikz,border=5]{standalone}
\usetikzlibrary{decorations}
\def\pgfdimgetwidth{%
  \pgfmathparse{\pgfpositionnodelatermaxx-\pgfpositionnodelaterminx}%
  \global\let\pgfdimwidth=\pgfmathresult%
}
\pgfdeclaredecoration{dimension}{draw}{%
\state{draw}[width=\pgfdecoratedpathlength]{
  % Get the width of the node without drawing it.
  \pgfpositionnodelater\pgfdimgetwidth%
  \node [node contents=, dimension label/.try];
  \pgfpositionnodelater\relax
  \pgfmathparse{\pgfdecoratedpathlength-\pgfdimwidth}%
  \ifdim\pgfdecoratedpathlength<0.375cm\relax
     \path (0,0) -- (\pgfdecoratedpathlength,0)
         node [rotate=\pgfdecoratedangle, midway, above=.25cm,, node contents=, dimension label/.try];
       \draw [->|] (-.25cm,0) -- (0,0);
       \draw [->|] (\pgfdecoratedpathlength+.25cm,0) -- (\pgfdecoratedpathlength,0);
  \else%
    \ifdim\pgfmathresult pt<0cm\relax%
       \draw [|<->|] (0,0) -- (\pgfdecoratedpathlength,0)
        node [rotate=\pgfdecoratedangle, midway, above=.25cm, node contents=, dimension label/.try];
    \else%
      \ifdim\pgfmathresult pt<.25cm\relax%
        \path (0,0) -- (\pgfdecoratedpathlength,0)
           node [rotate=\pgfdecoratedangle, midway, node contents=, dimension label/.try];
         \draw [->|] (-.25cm,0) -- (0,0);
         \draw [->|] (\pgfdecoratedpathlength+.25cm,0) -- (\pgfdecoratedpathlength,0);
      \else%
        \draw [|<->|] (0,0) --  (\pgfdecoratedpathlength,0)
        node [rotate=\pgfdecoratedangle, midway, node contents=, dimension label/.try] ;
      \fi%
    \fi%
  \fi%
}
}
\tikzset{%
  dimension/.style={
    decoration=dimension, decorate,
    dimension label/.style={
      node contents=#1, fill=white, font=\tiny, inner sep=0pt
    }
  }
}
\begin{document}
\begin{tikzpicture}[>=stealth]
\foreach \i [count=\y] in {0.125,0.25,0.5,1,2}
\draw [dimension=\i cm] (0,\y) -- (\i,\y);
\end{tikzpicture}

\end{document}

enter image description here

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.