Tikz 节点多层的背景颜色

Tikz 节点多层的背景颜色

我正在尝试绘制两个位于不同层的节点。背景层由“大”节点组成,前景层由“小”节点组成。只有大节点可以有背景色,而不会影响小节点的背景色。下面是 MWE 生成的图像。“小”节点及其背景应为白色。

在此处输入图片描述

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{backgrounds,scopes}
\usetikzlibrary{arrows,positioning,shapes.geometric}

\begin{document}

\begin{tikzpicture}[remember picture]

    {[on background layer]
        \node (rect) at (4,2) [draw,thick,minimum width=2cm,minimum height=2cm, fill=red!30] {};
    }

    \node (smallRect) at (4,2) [draw,thick,minimum width=1cm, minimum height=1cm] {Small};

\end{tikzpicture}

\end{document}

我认为背景 TikZ 库提供的背景层应该可以工作,但是我误解了它吗?

答案1

我会不是将较小的节点填充为白色。这是因为如果后面有东西,它将被覆盖。相反,我建议使用even odd rule以避免较小的节点被填充。

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{backgrounds,scopes}

\begin{document}

\begin{tikzpicture}[remember picture]

    \node (rect) at (4,2) [draw,thick,minimum width=2cm,minimum height=2cm] {};
    \node (smallRect) at (4,2) [draw,thick,minimum width=1cm, minimum height=1cm] {Small};
    {[on background layer]
    \fill[even odd rule,red!30] (rect.south west) rectangle (rect.north east)
    (smallRect.south west) rectangle (smallRect.north east); 
    }
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

对于您的节点,您不需要使用背景层。节点按代码的顺序绘制。因此,如果您首先用红色填充编写较大的节点,然后用白色填充较小的节点,您将得到以下结果:

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[
box/.style args = {#1/#2}{draw, fill=#1, minimum size=#2}
                    ]
\node (rect)        [box=red!30/2cm] {};
\node (smallRect)   [box=white/1cm] {Small};
    \end{tikzpicture}
\end{document}            

附录: 受到@Schrödinger 的猫回答的启发......

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[
box/.style = {minimum size=#1}
                    ]
\node   (Rout)    [box=2cm]   {};
\node   (Rin)     [box=1cm]   {Small};
\draw[even odd rule,fill=red!30]      % borrowed from @Schrödinger's cat answer
        (Rout.south west) rectangle (Rout.north east)
        (Rin.south west)  rectangle (Rin.north east); 
    \end{tikzpicture}
\end{document}            

结果和以前一样。

答案3

您甚至不需要两条线就能达到这个效果!只需使用线\nodes的属性即可……double

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
    \node[double=red!30,double distance=10pt,draw=black,fill=white,minimum size=1.5cm] (smallRect)    {Small};
    \end{tikzpicture}
\end{document}            

在此处输入图片描述

相关内容