我有一个简单的例子,用箭头线连接两个节点。但我怀疑这不是做这种事情的最好方法。
要求是:
- 节点位置固定但距离可能未知。
- 连接线应为垂直线或水平线。
- 在两个节点的中间改变方向。
当前 MWE 如下:
\documentclass[a4paper,10pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,positioning}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\setlength\PreviewBorder{5pt}%
\tikzset{
block/.style={draw,text width=2em,minimum height=1em,align=center},
arrow/.style={->}
}
\begin{document}
\begin{tikzpicture}[>=stealth']
\node[block] (N1) {N1};
\node[block,below=1cm of N1,xshift=-1cm] (N2) {N2};
\path (N1) -- (N1 |- N2) coordinate [midway] (C);
\draw [arrow] (N2) |- (C) -| (N1);
\path[fill=red] (C) circle (2pt); % help dot,not must have
\end{tikzpicture}
\end{document}
当前输出为:
答案1
您可以使用calc
库来避免单独绘制路径。这就是您想要的吗?
\documentclass[border=5pt,tikz]{standalone}
\usetikzlibrary{arrows,positioning,calc}
\tikzset{
block/.style={draw,text width=2em,minimum height=1em,align=center},
arrow/.style={->}
}
\begin{document}
\begin{tikzpicture}[>=stealth']
\node[block] (N1) {N1};
\node[block,below=1cm of N1,xshift=-1cm] (N2) {N2};
\draw [arrow] (N2) |- ($(N1)!1/2!(N1 |- N2)$) coordinate (C) -| (N1);
\end{tikzpicture}
\end{document}
或者你可以定义一个pic
:
\documentclass[border=5pt,tikz]{standalone}
\usetikzlibrary{arrows,positioning,calc}
\tikzset{
block/.style={draw,text width=2em,minimum height=1em,align=center},
arrow/.style={->},
pics/block connector/.style n args=2{
code={
\path [pic actions] (#1) |- ($(#2)!1/2!(#2 |- #1)$) -| (#2);
},
},
}
\begin{document}
\begin{tikzpicture}[>=stealth']
\node[block] (N1) {N1};
\node[block, below=1cm of N1, xshift=-1cm] (N2) {N2};
\pic [draw=green, arrow] {block connector={N2.north west}{N1.north west}};
\pic [draw=red, arrow] {block connector={N2.south east}{N1.south east}};
\pic [draw=blue, arrow] {block connector={N1}{N2}};
\end{tikzpicture}
\end{document}
答案2
这个怎么样?
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows,positioning,calc}
\tikzset{
block/.style={draw,text width=2em,minimum height=1em,align=center},
arrow/.style={->}
}
\newcommand\connect[2]{\path[draw,arrow] (#1) |- ($(#1)!1/2!(#2)$) -| (#2)}
\begin{document}
\begin{tikzpicture}[>=stealth']
\node[block] (N1) {N1};
\node[block,below=1cm of N1,xshift=-1cm] (N2) {N2};
\connect{N1}{N2};
\end{tikzpicture}
\end{document}
结果相同: