如何为节点、绘制添加节点样式选项 layer=background……?

如何为节点、绘制添加节点样式选项 layer=background……?

是否可以通过向节点添加样式选项来定义 tikz 样式来访问背景层,而不必将整个节点放在环境中?这是一个示例代码:

\documentclass[tikz]{standalone}

\usepackage{tikz}    
\usetikzlibrary{backgrounds}

\begin{document}

\pgfdeclarelayer{bg}
\pgfsetlayers{bg,main}

\tikzset{
  background/.style={%
    execute at begin node={\begin{pgfonlayer}{bg}},
    execute at end node={\end{pgfonlayer}}
  }
}

\begin{tikzpicture}

\draw[thick,red] (-1,0) -- (1,0);

\begin{pgfonlayer}{bg}
\node[circle,fill=blue,label={blue node behind red line, good}] at (0,0){};
\end{pgfonlayer}

\draw[thick,red] (-1,-1) -- (1,-1);
\node[circle,fill=blue,background,label={blue node above red line, bad}] at (0,-1){};

\end{tikzpicture}

\end{document}

正如您在我的示例中所看到的,我已经尝试添加自定义样式,但没有效果。老实说,我不太明白如何定义新样式,这更像是复制粘贴的结果,所以它可能指向了一个完全错误的方向。

答案1

感谢 Torbjørn T. 的评论和 Loop Space 的回答(https://tex.stackexchange.com/a/20426)我找到了一个可以正常工作的版本:

\documentclass[tikz]{standalone}

\pgfdeclarelayer{bg}
\pgfdeclarelayer{bbg}
\pgfsetlayers{bbg,bg,main}

%%% see https://tex.stackexchange.com/a/20426
\makeatletter
\pgfkeys{%
  /tikz/on layer/.code={
    \pgfonlayer{#1}\begingroup
    \aftergroup\endpgfonlayer
    \aftergroup\endgroup
  },
  /tikz/node on layer/.code={
    \gdef\node@@on@layer{%
      \setbox\tikz@tempbox=\hbox\bgroup\pgfonlayer{#1}\unhbox\tikz@tempbox\endpgfonlayer\egroup}
    \aftergroup\node@on@layer
  },
  /tikz/end node on layer/.code={
    \endpgfonlayer\endgroup\endgroup
  }
}
\def\node@on@layer{\aftergroup\node@@on@layer}
\makeatother
%%%

\begin{document}   

\begin{tikzpicture}

\draw[thick,red] (-1,0) -- (1,0);

\begin{pgfonlayer}{bg}
\node[circle,fill=blue,label={blue node behind red line, good}] at (0,0){};
\end{pgfonlayer}
\begin{pgfonlayer}{bbg}
\draw[thick,black] (-1,-0.1) -- (1,-0.1);
\end{pgfonlayer}

\draw[thick,red] (-1,-1) -- (1,-1);
\node[circle,fill=blue,node on layer=bg,label={blue node above red line, bad}] at (0,-1){};
\draw[thick,black,on layer=bbg] (-1,-1.1) -- (1,-1.1);

\end{tikzpicture}

\end{document}

在此处输入图片描述

笔记:\node[node on layer=...]我添加了一条黑线来显示和的不同语法\draw[on layer=...]

相关内容