我想绘制一个交叉图,为此我有一个带坐标的数组。
现在我循环遍历它们并计算坐标之间的距离,如果它低于圆的半径,就应该画一条线。
我可以用某种\path let \p1 ... \n1 = veclen()
东西来计算距离,但是我不能用这个距离进行比较,而只能在一条路径中使用它。
我该怎么办?
这是我现在的 tikzpicture:
\begin{tikzpicture}[scale=0.5]
\newcommand{\centers}{(0,1),(0,0),(5,3),(2,1),(0.5,1),(4,3),(0,5),(1.6,3.5),(6,0.5)}
\foreach [count=\i] \coord in \centers{\draw \coord circle(1) node{\i};}
\foreach \coord in \centers{\fill \coord circle(0.15);}
\foreach [count=\i]\a in \centers{
\foreach [count=\j]\b in \centers{
\ifthenelse{\i < \j}{
% calculating distance between \a and \b
% and drawing lines here
}{};
}
}
\end{tikzpicture}
答案1
你可以像\ifnum
这样使用\ifdim
:
\documentclass[tikz,border=7mm]{standalone}
\usetikzlibrary{calc}
\begin{document}
\newcommand{\centers}{(0,1),(0,0),(5,3),(2,1),(0.5,1),(4,3),(0,5),(1.6,3.5),(6,0.5)}
\begin{tikzpicture}
% link centers if circles intersect
\foreach[count=\i] \a in \centers {
\foreach[count=\j] \b in \centers {
\ifnum \j < \i
\draw[red] let \p1=\a, \p2=\b, \n1={veclen(\x1-\x2,\y1-\y2)} in
{\ifdim \n1 < 2 cm \a -- \b \fi};
\fi
}
}
% draw circles
\foreach [count=\i] \coord in \centers{\draw \coord circle(1);}
\foreach \coord in \centers{\fill \coord circle(2pt);}
\end{tikzpicture}
\end{document}
答案2
我通过一些额外的宏解决了这个问题veclen
。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\makeatletter
\def\veclen#1=#2->#3;{%
\edef\x{\noexpand\@veclen\noexpand#1#2#3}%
\x
}
\def\@veclen#1(#2,#3)(#4,#5){%
\pgfmathsetmacro#1{veclen(#2-#4,#3-#5)}%
}
\makeatother
\begin{document}
\begin{tikzpicture}[scale=0.5]
\def\thresh{2.0}
\def\centers{(0,1),(0,0),(5,3),(2,1),(0.5,1),(4,3),(0,5),(1.6,3.5),(6,0.5)}
\foreach \coord [count=\i] in \centers {
\node[draw,fill,circle,inner sep=1pt] (n-\i) at \coord {};
\draw (n-\i) circle (1);
}
\foreach \a [count=\i] in \centers{
\foreach \b [count=\j] in \centers{
\ifnum\i<\j
\veclen\dist=\a->\b;
\ifdim\dist pt<\thresh pt
\draw[red] (n-\i) -- (n-\j);
\fi
\fi
}
}
\end{tikzpicture}
\end{document}