使用“append after command”为 tikz 节点添加多种可组合样式

使用“append after command”为 tikz 节点添加多种可组合样式

我正在尝试构建一个小型绘图库,其中每个节点都具有相同的基础,但可以使用各种选项进行注释,这将导致在节点内/上绘制额外的东西。我目前正在尝试通过使用 append after 命令来实现我想要的样式,但组合多个样式(每个样式都有一个 append after)会给我带来错误:

ERROR: Package pgf Error: No shape named  is known.

这是一个例子。我希望节点 (d) 既被划掉又带有红色框。(实际的绘制并不重要,我的问题是如何组合多种样式):

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes, fit}

\begin{document}
\begin{tikzpicture}
  \tikzset{
    main/.style={
      circle, minimum size=6mm, very thick,draw
    },
    crossed out/.style={
      append after command={
        node [
          fit=(\tikzlastnode),
          draw=red,
          thick,
          inner sep=-\pgflinewidth,
          cross out
        ] {}
      }
    },
    red box/.style={
      append after command={
        node [
          fit=(\tikzlastnode),
          fill=red,
          text width=2mm,
          inner sep=-\pgflinewidth,
          rectangle
        ] {}
      }
    }
}

\node [main] (a) {A};
\node [main,crossed out,right of = a] (b) {B};
\node [main,red box,right of = b] (c) {C};

% this one doesn't work
\node [main,red box,crossed out,right of = c] (d) {D};

\end{tikzpicture}
\end{document}

在此先感谢大家的帮助!我显然愿意用完全不同的方法来实现这种“可组合”的风格。

答案1

一种方法是将节点上的名称记录为其他名称,并在以后的样式中使用该名称。但您也可以改用pics,以减少麻烦并获得更大的灵活性(在 TikZ v3.0 中)。

\documentclass[tikz]{standalone}
\usetikzlibrary{shapes, fit}
\begin{document}
\begin{tikzpicture}
  \tikzset{
    main/.style={circle, minimum size=6mm, very thick,draw,keep name},
    keep name/.style={prefix after command={\pgfextra{\let\fixname\tikzlastnode}}},
    crossed out/.style={
      append after command={
        node [
          fit=(\fixname) ,
          draw=red,
          thick,
          inner sep=-\pgflinewidth,
          cross out
        ] {}
      }
    },
    red box/.style={
      append after command={
        node [
          fit=(\fixname) ,
          fill=red,
          text width=2mm,
          inner sep=-\pgflinewidth,
          rectangle
        ] {}
      }
    }
}
\node [main] (a) {A};
\node [main,crossed out,right of = a] (b) {B};
\node [main,red box,right of = b] (c) {C};
\node [main,red box,crossed out,right of = c] (d) {D};
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容