如何在每次调用自定义命令时旋转颜色?

如何在每次调用自定义命令时旋转颜色?

我正在尝试这样做:

\print{Hello!} % to be printed in red
\print{How are you?} % to be printed in green
\print{I'm good!} % to be printed in blue
\print{Bye!} % again in red

我只想让\print命令从预定义的“调色板”(颜色列表)中选择下一种颜色。调色板完成后,它应该从第一个颜色开始。这怎么可能呢?

答案1

这是一个简单的实现。它使用\ifcase构造来遍历计数器的值并相应地设置颜色。当我们到达最后一个时,我们会重置。请注意,计数器在 latex 中是全局的。

\documentclass[a4paper]{article}
\usepackage{xcolor}
\newcounter{colrot}
\newcommand\print[1]{%
  \stepcounter{colrot}%
  \ifcase\value{colrot}\relax% 0 ignoreed
  \or\color{red}% 1
  \or\color{green}% 2
  \or\color{blue}\setcounter{colrot}{0}% 3
  \fi%
  #1%
}
\begin{document}

\print{Hello!} % to be printed in red
\print{How are you?} % to be printed in green
\print{I'm good!} % to be printed in blue
\print{Bye!} % again in red

\end{document}

答案2

\print每次使用时,这都会保留一堆颜色并循环。

\documentclass{article}
\usepackage{xcolor}

\makeatletter
\newcommand\colorlist{{red}{green}{blue}{black}{purple}}
\newcommand\print[1]{%
    \expandafter\textcolor\expandafter{\expandafter\@car\colorlist\@nil}{#1}%
    \edef\colorlist{\expandafter\@cdr\colorlist\@nil {\expandafter\@car\colorlist\@nil}}%
}
\makeatletter

\begin{document}
\print{foo} \print{bar} \print{baz} \print{foo} \print{bar} \print{baz}
\end{document}

输出

但是,颜色数量必须至少为 3 种,否则一些括号会被剥离。对于 2 种颜色,只需进行简单的切换即可:

\let\printaux=A
\newcommand\print[1]{\if A\printaux \let\printaux=B\textcolor{red}{#1}\else \let\printaux=A\textcolor{blue}{#1}\fi}

相关内容