如何填充使用 tikz fit 创建的节点

如何填充使用 tikz fit 创建的节点

我想在一组节点周围绘制一个边界框来表示关系。我使用 tikz fit 页面执行此操作,如附件代码所示。

我现在想改变边界框的背景颜色。

当我在计算填充区域的节点中添加填充时,我的节点被填充覆盖。如何填充边界框区域而不覆盖我现有的节点。

我是否要再次重新绘制节点?或者有更好的解决方案吗?

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,fit}

\tikzset{block/.style={rectangle, draw}}

\begin{document}
\begin{tikzpicture}

\node[block] (node1) { Node1 };
\node[block, right=of node1] (node2) { Node2 };
\node[block, below=of node2] (node3) { Node3 };

\node [
   dashed,
   draw,
   %fill={rgb:red,230;green,84;blue,0},    %% This over writes my nodes
   inner ysep=0.25cm,inner xsep=0.25cm,
   fit=(node1)(node2)(node3)] (box) {};

\end{tikzpicture}
\end{document}

答案1

另一种解决方案(不使用backgrounds库),如果您可以将所有节点放在同一路径上,则是使用选项behind path,如下所示:

\documentclass[tikz,border=7pt]{standalone}
\usetikzlibrary{positioning,fit}

\begin{document}
  \begin{tikzpicture}[block/.style={rectangle, draw, fill=white}]
    \path
      node[block] (node1) { Node1 }
      node[block, right=of node1] (node2) { Node2 }
      node[block, below=of node2] (node3) { Node3 }
      node [behind path, % <------
            dashed,
            draw,
            fill={rgb:red,230;green,84;blue,0},
            inner sep=0.25cm,
            fit=(node1)(node2)(node3)] (box) {};
  \end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,fit,backgrounds}

\pgfdeclarelayer{background}
\pgfdeclarelayer{foreground}
\pgfsetlayers{background,main,foreground}

\tikzset{block/.style={rectangle, draw,fill=white}}

\begin{document}
\begin{tikzpicture}

\node[block] (node1) { Node1 };
\node[block, right=of node1] (node2) { Node2 };
\node[block, below=of node2] (node3) { Node3 };

\begin{pgfonlayer}{background}
\node [
   dashed,fill=red,
   draw,
   %fill={rgb:red,230;green,84;blue,0},    %% This over writes my nodes
   inner ysep=0.25cm,inner xsep=0.25cm,
   fit=(node1)(node2)(node3)] (box) {};

\end{pgfonlayer}

\end{tikzpicture}
\end{document}

答案3

以下是使用范围和 来实现此目的的一种方法local bounding box

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,backgrounds}

\tikzset{block/.style={rectangle, draw}}

\begin{document}
\begin{tikzpicture}

\begin{scope}[local bounding box=box1]
\node[block] (node1) { Node1 };
\node[block, right=of node1] (node2) { Node2 };
\node[block, below=of node2] (node3) { Node3 };
\path (box1.south west) ++(-.25cm,-.25cm)
      (box1.north east) ++(.25cm, .25cm);% add margins
\end{scope}

\begin{scope}[on background layer]
\draw[dashed,fill=red] (box1.south west) rectangle (box1.north east);
\end{scope}

\end{tikzpicture}
\end{document}

相关内容