为节点组创建背景

为节点组创建背景

我如何为节点组添加背景(但节点组是在绘制背景之前创建的)。问题是,如果我在创建组之前(即在调用宏 \graphcircuit 之前)绘制一个矩形,它将位于图形的顶部,而在另一边,如果没有组,我就无法绘制背景(我不知道组的大小)。

下面的代码来自答案 相对于一组节点定位节点 这是从答案中得出的 tikz:如何将列表作为 tikz 宏的参数传递并在宏内的 foreach 中使用它

\documentclass[tikz]{standalone}
\usetikzlibrary{fit}

\newcommand{\graphcircuit}[1]{
\begin{scope}
\def\myfitarray{}
\foreach[count=\n] \v in {#1}; % count the number of elements
\pgfmathsetmacro{\r}{\n*0.2} % set the node distance from (0,0)
\pgfmathsetmacro{\b}{90/\n} % evaluate the bend angle
\foreach[count=\i, evaluate=\i as \a using (\i-1)*360/\n] \v in {#1}
  \node [circle, draw, font=\scriptsize] (n-\i) at (\a:\r) {$\v$};
\foreach \i [remember=\i as \j (initially \n)] in {1,...,\n}{
  \draw[semithick,-stealth] (n-\j) to[bend right=\b] (n-\i);}
\foreach \x in {1,...,\n}{%
\expandafter\xdef\expandafter\myfitarray\expandafter{\myfitarray (n-\x)}}
\node[inner sep=2pt,fit=\myfitarray] (groupnode) {};
\end{scope}
}

\begin{document}
  \begin{tikzpicture}
    \graphcircuit{1:5,7:2,3:0,4:0,9:1}
    \node[font=\normalsize,anchor=south] (A) at (groupnode.north) {(A)}; 
    \fill[cyan!15] (groupnode.south west) rectangle (groupnode.north east);
  \end{tikzpicture}
\end{document}

答案1

绘制组后,您可以使用该backgrounds库来填充组后面的节点:

\documentclass[tikz]{standalone}
\usetikzlibrary{fit,backgrounds}

\newcommand{\graphcircuit}[1]{
  \begin{scope}
    \def\myfitarray{}
    \foreach[count=\n] \v in {#1}; % count the number of elements
    \pgfmathsetmacro{\r}{\n*0.2} % set the node distance from (0,0)
    \pgfmathsetmacro{\b}{90/\n} % evaluate the bend angle
    \foreach[count=\i, evaluate=\i as \a using (\i-1)*360/\n] \v in {#1}
    \node [circle, draw, font=\scriptsize] (n-\i) at (\a:\r) {$\v$};
    \foreach \i [remember=\i as \j (initially \n)] in {1,...,\n}{
      \draw[semithick,-stealth] (n-\j) to[bend right=\b] (n-\i);}
    \foreach \x in {1,...,\n}{%
      \expandafter\xdef\expandafter\myfitarray\expandafter{\myfitarray (n-\x)}}
    \node[inner sep=2pt,fit=\myfitarray] (groupnode) {};
  \end{scope}
}

\begin{document}
  \begin{tikzpicture}
    \graphcircuit{1:5,7:2,3:0,4:0,9:1}
    \node[font=\normalsize,anchor=south] (A) at (groupnode.north) {(A)};
    \scoped[on background layer]{
      \fill[cyan!15] (groupnode.south west) rectangle (groupnode.north east);}
  \end{tikzpicture}
\end{document}

节点组后面的背景填充

相关内容