[Tex/LaTex] TikZ: Calculate “pre length” based on path length

pgf-decorationstikz-pgf

I would like to automatically calculate the pre length value for a line decoration to be "centered". Let me explain it by this example:

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations.shapes}

\begin{document}
\begin{tikzpicture}[foo/.style={decorate,decoration={
    shape backgrounds,shape=circle,shape sep=2.5cm,pre=moveto,pre length=#1}}]
  \node at (0cm,0cm)  [label=below:0]  {};
  \node at (5cm,0cm)  [label=below:5]  {};
  \node at (9cm,0cm)  [label=below:9]  {};
  \node at (10cm,0cm) [label=below:10] {};
  \draw[foo=0cm]    (0cm,0cm) -- (10cm,0cm); % line 1
  \draw[foo=0cm]    (0cm,5mm) -- ( 9cm,5mm); % line 2
  \draw[foo=0.75cm] (0cm,1cm) -- ( 9cm,1cm); % line 3
\end{tikzpicture}
\end{document}

(How can I add a compiled version of the code? Do I have to manually compile and upload it as a image?)

compiled version

  • line 1 (bottom) is what I want: Circles from the start of the line (0,0) to its end (10,0).
  • line 2 (middle) shows the problem: If the paths length is not a multiple of shape sep, the first circle is at the paths start and there is nothing between the last circle and the paths end.
  • line 3 (top) shows how the problem should be handled: By setting pre length to the right value (or by some other method, if you have a better idea), the distance between the paths start and the first circle is the same as the distance between the last circle and the paths end.

Now my question is: How can I set pre length to (path length - shape sep)/2(path length - (number of circles - 1) * shape sep) / 2 (thanks to Altermundus for the correction)? Or is there a better solution to this?

Best Answer

I'm not sure of my formula but (path length - shape sep)/2is not very fine. You can use some values like \pgfmetadecoratedpathlength and \pgf@lib@shapedecoration@sep.

\documentclass{standalone}    
\usepackage{tikz}
\usetikzlibrary{decorations.shapes}

\begin{document} 
  \makeatletter
\begin{tikzpicture}%
   [foo/.style={decorate,
                decoration={shape backgrounds,
                            shape=circle,
                            shape sep=2.5cm,
                            pre=moveto,
   pre length=(\pgfmetadecoratedpathlength-%
              floor(\pgfmetadecoratedpathlength/\pgf@lib@shapedecoration@sep)*%
                     \pgf@lib@shapedecoration@sep)/2}}]
  \node at (0cm,0cm)  [label=below:0]  {};
  \node at (5cm,0cm)  [label=below:5]  {};
  \node at (9cm,0cm)  [label=below:9]  {};
  \node at (10cm,0cm) [label=below:10] {};
  \draw[foo] (0cm,1cm) -- ( 9cm,1cm); 
\end{tikzpicture}
\end{document}

enter image description here