Tikz 复制节点句柄

Tikz 复制节点句柄

我正在使用foreach它来绘制图片,需要先前绘制的节点和当前节点的节点句柄。之前我使用以下模式来保存单独的坐标:

\node (current) {first};

\foreach \i in {...} {
    \coordinate (prev) at (current.west);
    \node (current) {\i};

    \draw[->] (prev) -- (current);
};

% There might be better solutions for this with chains or so,
% however, this is only to demonstrate the pattern

如果需要从节点获取多个坐标,这很快就会变得很麻烦。有没有方法可以将整个复制nodehandleprev,以便prev.<anchor>(即prev.westprev.east)可以工作?


MWE:按照要求

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{automata, positioning}
\begin{document}
\begin{tikzpicture}
{[every node/.style={state}]
    \node (state) [initial] {$q_0$};
    \path[->] (state) edge [loop below] ();
    \foreach \i in {1,2,n} {
        \coordinate (prev) at (state.east);
        \node (state) [right=of prev] {$q_\i$};
        \path[->] (state) edge [loop below] ();
        \path[->] (prev) edge (state);
    }
}
\end{tikzpicture}
\end{document}

答案1

\pgfnodealias,可用于将节点数据从一个名称复制到另一个名称:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{automata, positioning}
\begin{document}
\begin{tikzpicture}
{[every node/.style={state}]
    \node (state) [initial] {$q_0$};
    \path[->] (state) edge [loop below] ();
    \foreach \i in {1,2,n} {
        \pgfnodealias{prev}{state}
        \node (state) [right=of prev] {$q_\i$};
        \path[->] (state) edge [loop below] ();
        \path[->] (prev) edge (state);
    }
}
\end{tikzpicture}
\end{document}   

结果

答案2

不确定这是否是您需要的,但您无需指定锚点即可以这种方式从一个节点到另一个节点绘制路径。这允许您使用变量而不是指定锚点。

我添加了一个额外的 foreach 来显示具有不同计数的多个 foreach 语句。

输出

图1

代码

\documentclass[margin=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{automata, positioning}

\tikzset{
    every node/.style={state, draw=none}
}

\begin{document}
\begin{tikzpicture}
\foreach \n [count=\sft] in {3,1,5,7,2,9}{
\begin{scope}[yshift=\sft*2 cm]
\node (A) [initial] {$q_0$};
\path[->] (A) edge [loop below] ();
    \foreach \i [remember=\i as \prev (initially A)] in {1,...,\n} {
        \node (\i) [right =of \prev] {$q_\i$};
        \path[->] (\i) edge [loop below] ();
        \path[->] (\prev) edge (\i);
    }
\end{scope}}
\end{tikzpicture}
\end{document}

答案3

另一个示例,foreach但有一对表示previous/present节点的值

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{automata, positioning}
\begin{document}
\begin{tikzpicture}
{[every node/.style={state}]
    \node (q0) [initial] {$q_0$};
    \path[->] (q0) edge [loop below] ();
    \foreach \i/\j in {0/1,1/2,2/n} {
        \node (q\j) [right=of q\i] {$q_\j$};
        \path[->] (q\j) edge [loop below] ();
        \path[->] (q\i) edge (q\j);
}    }
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容