我有一些坐标(比如 A、B、C)。
现在我做了这样的事情:\foreach \P in {A,B,C} \draw[fill=pink] (\P) circle[radius=2.5pt];
如果我说\foreach \P in {A,B,C,X} \draw[fill=pink] (\P) circle[radius=2.5pt];
我会得到错误No shape named 'X' is known.
所以我的问题是:我怎么能有像符号代码这样的东西
\ifcoordinateexist
\draw[fill=pink] (\P) circle[radius=2.5pt];
\else % nothing
\fi
我有一个简单的解决方案,也许使用 TikZ-tools?
\documentclass[border=2mm, tikz]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[]
\coordinate[label=A](A) at (0,0);
\coordinate[label=B](B) at (2,3);
\coordinate[label=C](C) at (1,1);
% Will work:
\foreach \P in {A,B,C} \draw[fill=pink] (\P) circle[radius=2.5pt];
%% Will not work:
%\foreach \P in {A,B,C,X} \draw[fill=pink] (\P) circle[radius=2.5pt];
% ---------> No shape named `X' is known.
\end{tikzpicture}
\end{document}
答案1
正如指出我之前的评论,
tikz 节点是全局定义的(也在Martin Scharrer 的原始答案),因此如果
X
在先前的 tikzpicture 中定义了一个节点,那么这个测试\ifcoorddefined
(这个答案) 将会失败。
这是一个增强的测试器,可以测试给定的节点是否在当前(由 内部使用的环境)\ifNodeDefined{<node name>}{<true>}{<false>}
中定义。pgfpicure
tikzpicture
\documentclass{article}
\usepackage{tikz}
\makeatletter
\long\def\ifcoorddefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\def\ifNodeDefined#1{%
\@ifundefined{pgf@sh@ns@#1}{\@secondoftwo}{%
\expandafter\ifx\csname pgf@sh@pi@#1\endcsname\pgfpictureid
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}%
}
\makeatother
\begin{document}
\begin{tikzpicture}
\coordinate[label=X] (X) at (1,0);
\coordinate[label=Y] (Y) at (0,1);
\end{tikzpicture}
\qquad
\begin{tikzpicture}[baseline=0pt]
\coordinate[label=A] (A) at (0,0);
\coordinate[label=B] (B) at (2,3);
\coordinate[label=C] (C) at (1,1);
\foreach \P in {A,B,C, X, Y, L, M}{
\ifcoorddefined{\P}
{\draw[fill=pink] (\P) circle[radius=2pt];}
{}
}
\node[anchor=north] at (1,-.5) {old tester};
\end{tikzpicture}
\qquad
\begin{tikzpicture}[baseline=0pt]
\coordinate[label=A] (A) at (0,0);
\coordinate[label=B] (B) at (2,3);
\coordinate[label=C] (C) at (1,1);
\foreach \P in {A,B,C, X, Y, L, M}{
\ifNodeDefined{\P}
{\draw[fill=pink] (\P) circle[radius=2pt];}
{}
}
\node[anchor=north] at (1,-.5) {new tester};
\end{tikzpicture}
\end{document}
答案2
我在这里找到了一个解决方案: https://tex.stackexchange.com/a/85531/46023
\documentclass[border=2mm, tikz]{standalone}
\usepackage{tikz}
\begin{document}
\makeatletter
\long\def\ifcoorddefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\makeatother
\begin{tikzpicture}[]
\coordinate[label=A](A) at (0,0);
\coordinate[label=B](B) at (2,3);
\coordinate[label=C](C) at (1,1);
\foreach \P in {A,B,C, X, Y, L, M}{
\ifcoorddefined{\P}{ \draw[fill=pink] (\P) circle[radius=2pt]; }{}
}
\end{tikzpicture}
\end{document}