TikZ-在声明节点“之后”更改节点的颜色

TikZ-在声明节点“之后”更改节点的颜色

节点声明后可以“更改”其颜色吗?forest即使我的问题是关于 TikZ 的,下面也是一个例子。

\documentclass{article}

\usepackage{forest}

\newcommand\colorafter[2]{
    % ???
}

\begin{document}
\begin{forest}
    [
        [$A$, red % I don't want to use this.
            [$B$, name = nB]
            [$C$, name = nC]
        ]
        [$D$, blue % I don't want to use that.
        ]
    ]
    \colorafter{nB}{red}
    \colorafter{nD}{blue}
\end{forest}

\end{document}

答案1

在此处输入图片描述

在示例中,所有节点都创建为蓝色节点。 A(左上)的颜色最后变为红色。底部节点只是为了提示我所选择的路径。

答案是针对 TikZ 的。该函数\aftercolorof}[2]{...在节点 #2 上创建一个颜色为 #1 的新节点,名称为 #2-2(以防您以后需要它)。

它基于@Henri Menke 给出的功能如何访问节点的标签文本?

\documentclass[11pt, border=1cm]{standalone}
\usepackage{tikz}

\makeatletter
\protected\def\tikz@fig@main#1{%
  \expandafter\gdef\csname labeltextof@\tikz@fig@name\endcsname{#1}%
  \iftikz@node@is@pic%
    \tikz@node@is@picfalse%
    \tikz@subpicture@handle{#1}%
  \else%
    \tikz@@fig@main#1\egroup%
  \fi}
\makeatother

\newcommand\labeltextof[1]{\csname labeltextof@#1\endcsname}
\newcommand{\aftercolorof}[2]{% #1 is the color, #2 us the node
  \path (#2.center) node[#1] (#2-2) {\labeltextof{#2}};
}

\begin{document}

\begin{tikzpicture}[
  every node/.style={draw, circle, color=blue, text=blue},
  spear/.style={->, very thin, shorten <=2pt, shorten >=2pt,}
  ]
  \path (0, 0) node (nA) {$A$};
  \path (2, 0) node (nB) {$B$};

  \path (1, -2) node[label={
    [rectangle, text width=8em]-80:this is the node nC with nA's content
  }] (nC) {\labeltextof{nA}};

  \path
  (nA) edge [spear, right] (nB)
  (nA) edge [spear, right] (nC);

  % changing the color
  \aftercolorof{red}{nA}
\end{tikzpicture}

\end{document}

下面是一个示例,说明该解决方案如何工作forest

\documentclass{article}

\usepackage{tikz}
\usepackage{forest}

\makeatletter
\protected\def\tikz@fig@main#1{%
  \expandafter\gdef\csname labeltextof@\tikz@fig@name\endcsname{#1}%
  \iftikz@node@is@pic%
    \tikz@node@is@picfalse%
    \tikz@subpicture@handle{#1}%
  \else%
    \tikz@@fig@main#1\egroup%
  \fi}
\makeatother

\newcommand\labeltextof[1]{\csname labeltextof@#1\endcsname}
\newcommand{\aftercolorof}[2]{% #1 is the color, #2 us the node
  \path (#2.center) node[#1] (#2-2) {\labeltextof{#2}};
}

\begin{document}

\begin{forest}
    [
        [$A$, name = nA
            [$B$]
            [$C$]
        ]
        [$D$, name = nD
        ]
    ]
    \aftercolorof{red}{nA}
    \aftercolorof{blue}{nD}
\end{forest}

\end{document}

相关内容