pgfkeys 错误:我不知道密钥“/tikz/green”

pgfkeys 错误:我不知道密钥“/tikz/green”

我想根据计数器中存储的数字设置矩形的填充颜色。这是我的尝试:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\background}[1]{%
\begin{tikzpicture}[overlay,remember picture]
\fill [#1]
        ($ (current page.north west) + (.7cm,-.7cm) $)
        rectangle
        ($ (current page.south east) + (-.7cm,.7cm) $);
\end{tikzpicture}
}

\newcounter{test}
\setcounter{test}{1}
\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

\begin{document}
\background{green} % everything is good
\newpage
\background{\chooseColor} % throwing the error shown below
\end{document}

虽然\background{green}得到了我想要的结果,但却\background{\chooseColor}引发了以下错误:

! Package pgfkeys Error: I do not know the key '/tikz/green ' and I am going to
 ignore it. Perhaps you misspelled it. 

我从错误中得出结论,该值\background{\chooseColor}已被正确评估为“绿色”,但我收到了该错误消息。我是否错过了什么?我将很高兴得到帮助!

答案1

错误来自于你定义

\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

因此,您分配\chooseColor带有greenred带有尾随空格的空间。该空间被接管给 TiZ,但green(带有空格)对 Ti 来说不是有效颜色Z(也不是red)。

删除空格它就可以工作了:

\newcommand{\chooseColor}{\ifnum\thetest=1 green\else red\fi}

答案2

删除空格的另一种方法是使用/.expanded键处理程序。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\background}[1]{%
\begin{tikzpicture}[overlay,remember picture]
\fill [#1]
        ($ (current page.north west) + (.7cm,-.7cm) $)
        rectangle
        ($ (current page.south east) + (-.7cm,.7cm) $);
\end{tikzpicture}
}

\newcounter{test}
\setcounter{test}{1}
\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

\begin{document}
\background{green} % everything is good
\newpage
\background{color/.expanded=\chooseColor} % throwing the error shown below
\end{document}

相关内容