在路径的每个点处创建一个坐标节点

在路径的每个点处创建一个坐标节点

我如何创建一个TikZ/pgf样式,以便在路径的每个点上放置一个应自动命名的坐标?

因此下面的代码

\draw[put coordinates](0,0)--(3,2)--(4,7)--(-2,1);

应基本与以下内容相同:

\draw(0,0)--(3,2)--(4,7)--(-2,1);
\coordinate(mypathcoordinate1) at (0,0);
\coordinate(mypathcoordinate2) at (3,2);
\coordinate(mypathcoordinate3) at (4,7);
\coordinate(mypathcoordinate4) at (-2,1);

答案1

您可以使用show path construction通过 a 施加的装饰postaction来放置coordinates。这样,底层路径根本不会改变。

以下样式put coordinates采用可选参数来命名坐标(默认为coordinate):

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing}
\newcounter{coordinateindex}


\begin{document}
\tikzset{
    put coordinates/.style={
        initialize counter/.code={
            \setcounter{coordinateindex}{0}
        },
        initialize counter,
        decoration={
            show path construction,
            moveto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentfirst);
            },
            lineto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
            curveto code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
            closepath code={
                \stepcounter{coordinateindex}
                \coordinate (#1\thecoordinateindex) at (\tikzinputsegmentlast);
            },
        },
        postaction={decorate}
    },
    put coordinates/.default=coordinate
}

\begin{tikzpicture}
\draw [put coordinates] (0,0) -- (3,2) to [out=90, in=0] (4,7)-- (-2,1);

\foreach \i in {1,...,\thecoordinateindex}{
    \fill (coordinate\i) circle [radius=2pt] node [above left] {\i};
}

\draw [red, put coordinates=secondpath] (0,1) -- (5,4) -- (4,1);
\foreach \i in {1,...,\thecoordinateindex}{
    \fill (secondpath\i) circle [radius=2pt] node [above left] {\i};
}
\end{tikzpicture}

\end{document}

相关内容