如何将交点保存为节点以供以后多次使用?

如何将交点保存为节点以供以后多次使用?

以下 MWE 将无法编译,因为\n无法识别\foreach

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
    \draw [red, smooth, name path=first] plot coordinates {(1,1)(2,3)(4,6)(5,2)(7,5)};
    \draw [blue, smooth, name path=second] plot coordinates {(1,5)(2,1)(4,3)(5,5)(7,1)};
    \path [name intersections={of=first and second, total=\n}];
    \foreach \i in {1,...,\n}{\draw (intersection-\i) circle [radius=3pt];}
\end{tikzpicture}
\end{document}

我的目标是将交叉点保存为节点,以便以后多次使用。如何做到这一点?

答案1

我认为问题在于该\n命令仅在当前 TikZ 命令的范围内定义(即在您的示例中的命令范围内\path)。以下修复将您的\path\foreach命令组合成一个\draw命令。它与给出的示例非常相似13.3.2 任意路径的交点TikZ 手册。

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
    \draw [red, smooth, name path=first] plot coordinates {(1,1)(2,3)(4,6)(5,2)(7,5)};
    \draw [blue, smooth, name path=second] plot coordinates {(1,5)(2,1)(4,3)(5,5)(7,1)};
    \draw [name intersections={of=first and second, total=\n}]  
      \foreach \i in {1,...,\n}{(intersection-\i) circle [radius=3pt]};
\end{tikzpicture}
\end{document}

更新 1。我现在明白您希望将节点保存在单个命令的范围之外。按照 Andrew 在下面的评论中的建议,您可以使用命令定义节点\coordinate,如下所示。

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
    \draw [red, smooth, name path=first] plot coordinates {(1,1)(2,3)(4,6)(5,2)(7,5)};
    \draw [blue, smooth, name path=second] plot coordinates {(1,5)(2,1)(4,3)(5,5)(7,1)};
    \draw [name intersections={of=first and second, total=\n}]  
      \foreach \i in {1,...,\n} {(intersection-\i) coordinate (red-blue-intersection-\i)};
    \draw (red-blue-intersection-1) circle [radius=3pt];
    \draw (red-blue-intersection-2) circle [radius=3pt];
    \draw (red-blue-intersection-3) circle [radius=3pt];
\end{tikzpicture}
\end{document}

更新 2。\n您可能还希望数字节点,以脱离范围。然后,\draw上面代码中的这三个命令可以用循环代替。我不知道有什么“好”的方法来做到这一点,但这里有一个似乎可行的黑客方法。

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}
    \draw [red, smooth, name path=first] plot coordinates {(1,1)(2,3)(4,6)(5,2)(7,5)};
    \draw [blue, smooth, name path=second] plot coordinates {(1,5)(2,1)(4,3)(5,5)(7,1)};
    \draw [execute at begin node={\global\let\n=\n}, name intersections={of=first and second, total=\n}]  
      \foreach \i in {1,...,\n} {(intersection-\i) coordinate (red-blue-intersection-\i)};
    \foreach \i in {1,...,\n}
      \draw (red-blue-intersection-\i) circle [radius=3pt];
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容