如何连接各种保存箱的对象?

如何连接各种保存箱的对象?

当我使用 savebox/usebox 命令时,有时我必须从某个保存箱中某个对象的特定节点绘制一些箭头指向其他保存箱中的另一个对象。我该如何自动完成此操作?“自动”是指使用节点名称而不是明确的坐标值。例如,我如何在以下 MWE 中将c1in连接Cs1in ?S

\documentclass[tikz, border=2mm]{standalone}

\newsavebox{\cR}
\savebox{\cR}{\hspace{0.1ex}\tikz[baseline=0.1em]{%
  \node[draw, circle, inner sep = 0, minimum size = 1.4mm](c1){};}%
 \hspace{0.1ex}}

\newsavebox{\sQ}
\savebox{\sQ}{\hspace{0.1ex}\tikz[baseline=0.1em]{%
  \node [shape=rectangle, draw, fill=gray!30, inner sep=0pt, minimum width=0.9em, minimum height=0.9em] (s1) {};}%
 \hspace{0.1ex}}

\begin{document}

 \begin{tikzpicture}
  \node[] (C) at (0,0) {\usebox{\cR}};
  \node[] (S) at (0,1) {\usebox{\sQ}};
 \end{tikzpicture}
\end{document}

答案1

您可以使用节点的名称(C)和(S)`,然后将它们连接起来

在此处输入图片描述


如果您希望在各个图片元素内建立连接,最好使用pic而不是usebox

下面我定义两张图片:

  1. my square它绘制三个正方形,分别名为-s1-s2-s3
  2. my circle它绘制了三个圆圈,分别名为-c1-c2

如果你用 indivudla 来命名每个节点pic,那么你就可以连接它们:

在此处输入图片描述


代码:

\documentclass[border=2mm]{standalone}
\usepackage{tikz}

\newsavebox{\cR}
\savebox{\cR}{\hspace{0.1ex}\tikz[baseline=0.1em]{%
  \node[draw, circle, inner sep = 0, minimum size = 1.4mm](c1){};}%
 \hspace{0.1ex}}

\newsavebox{\sQ}
\savebox{\sQ}{\hspace{0.1ex}\tikz[baseline=0.1em]{%
  \node [shape=rectangle, draw, fill=gray!30, inner sep=0pt, minimum width=0.9em, minimum height=0.9em] (s1) {};}%
 \hspace{0.1ex}}

\begin{document}

 \begin{tikzpicture}
  \node[inner sep=0pt, outer sep=0pt] (C) at (0,0) {\usebox{\cR}};
  \node[inner sep=0pt, outer sep=0pt] (S) at (0,1) {\usebox{\sQ}};

  \draw [red] (C) -- (S);
 \end{tikzpicture}
\end{document}

代码:使用pics

\documentclass{article}
\usepackage{tikz}

\tikzset{Circle Style/.style={
  draw, 
  circle, 
  inner sep=0pt, 
  minimum size=1.4mm,
}}
\tikzset{Square Style/.style={
  shape=rectangle, 
  draw, 
  fill=gray!30, 
  inner sep=0pt, 
  minimum width=0.9em, 
  minimum height=0.9em,
}}

\tikzset{
  my square/.pic={% Define a .pic to draw three squares and name each of them
      code={
          \node at (0,0) [Square Style] (-s1) {$s_1$};
          \node at (1,0) [Square Style] (-s2) {$s_2$};
          \node at (2,0) [Square Style] (-s3) {$s_3$};
      }
  },
  my circle/.pic={% Define a .pic to draw two circles and name each of them
      code={
          \node [Circle Style] (-c1) at (0,0) {$c_1$};
          \node [Circle Style] (-c2) at (1,0) {$c_2$};
      }
  },
}

\begin{document}
\begin{tikzpicture}
    %% These two lines replace the \usebox
    \pic (MySq) at (0,0)   {my square};
    \pic (MyCr) at (0,-2)  {my circle};

    %% Now you can connect between the pics ans even within a pic
    \draw [red,     thick, ->] (MySq-s1) -- (MyCr-c2);
    \draw [blue,    thick, ->] (MySq-s3) -- (MyCr-c1);
    \draw [magenta, thick, ->] (MySq-s2.north) to[out=90, in=90] (MySq-s3.north);
\end{tikzpicture}

\end{document}

相关内容