我正在尝试找出嵌套tikz
具有不同背景颜色的节点的最佳方法。我希望“内部”节点在背景颜色方面“获胜”。目前,“外部”节点(“适合”)总是“获胜”。有没有更好的方法来解决这个问题?
一个简单的例子:将一个背景颜色为红色的内部节点嵌套在一个背景颜色为蓝色的外部节点中:
\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
% \begin{tikzpicture}%
% \node (inner) [draw] {foo-inner};%
% \node (outer) [draw,fit=(inner)] {};%
% \end{tikzpicture}%
% \begin{tikzpicture}%
% \node (inner) [draw,fill=red] {foo-inner};%
% \node (outer) [draw,fit=(inner)] {};%
% \end{tikzpicture}%
\begin{tikzpicture}%
\node (inner) [draw,fill=red] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\end{tikzpicture}%
\end{document}%
答案1
您也可以尝试将拟合节点发送到background
图层
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit,backgrounds}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red] {foo-inner};%
\node (inner2) [draw,fill=green] at (2,2) {foo-inner2};%
\begin{scope}[on background layer]
\node (outer) [draw,fill=blue,fit=(inner) (inner2)] {};%
\end{scope}
\end{tikzpicture}%
\end{document}
答案2
请注意,这更像是黑客行为:
如果你颠倒顺序“出现”(见下文注释)以产生预期的结果:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\end{tikzpicture}%
\begin{tikzpicture}%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\end{tikzpicture}%
\end{document}%
笔记:
正如杰克正确指出的那样,上述解决方案是有效的仅有的因为第一个tikzpicture
。所以,一般来说,仅仅颠倒顺序是行不通的。但是,你可以在顶部重复你想要的节点:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\node (outer) [draw,fill=blue,fit=(inner)] {};%
\node (inner) [draw,fill=red,fill] {foo-inner};%
\end{tikzpicture}%
\end{document}%
答案3
这是来自的解决方案pgfmanual.pgf
:
\documentclass[border=1pt, tikz]{standalone}
\usetikzlibrary{fit, backgrounds}
\begin{document}
\begin{tikzpicture}[level distance=8mm]
\node (root) {root}
child { node (a) {a} }
child { node (b) {b}
child { node (d) {d} }
child { node (e) {e} } }
child { node (c) {c} };
\begin{pgfonlayer}{background}
\node[fill=red!20,inner sep=0pt,circle,fit=(root) (b) (d) (e)] {};
\node[fill=blue!20,inner sep=0pt,circle,fit=(b) (c) (e)] {};
\end{pgfonlayer}
\end{tikzpicture}
\end{document}
如果您使用许多嵌套节点,请查看pgfdeclarelayer
和pgfsetlayers
。
\pgfdeclarelayer{background}
\pgfdeclarelayer{foreground}
\pgfsetlayers{background,main,foreground}
这将定义两个附加层并设置它们的顺序。