我有一个依赖于循环内计数器的递归宏tikz
\foreach
。我还没有实现的是如何让 tikz 样式(我称之为 fillMod)依赖于计数器值(即取决于 \n 是奇数还是偶数)。以下是我目前拥有的 MWE。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3,
fillEven/.style={fill=red},
fillOdd/.style= {fill=blue},
fillMod/.style= {}]
\coordinate (A0) at (0,0);
\foreach \n in {1,2,...,#1}
{
\draw[fillMod,scale={pow(0.8,\n)}] (A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0] (D0);
}
\end{tikzpicture}
}
\pic{2}
\pic{3}
\pic{4}
\pic{5}
\end{document}
我知道我可以在循环中定义两条\draw
路径,一条用于红色,一条用于蓝色,但这意味着我只能生成包含偶数个方块的图片。有办法吗?
答案1
也许是这样的。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]
\coordinate (A0) at (0,0);
\foreach \n in {1,2,...,#1}
{
\ifodd\n
\tikzset{fillMod/.style={fill=blue}}
\else
\tikzset{fillMod/.style={fill=red}}
\fi
\draw[fillMod,scale={pow(0.8,\n)}] (A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0] (D0);
}
\end{tikzpicture}
}
\begin{document}
\pic{2}
\pic{3}
\pic{4}
\pic{5}
\end{document}
答案2
这是没有明确测试的解决方案。第二个示例展示了具有四种样式的示例。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]
\tikzset{
fill 0/.style={fill=red},
fill 1/.style= {fill=blue},
}
\coordinate (A0) at (0,0);
\foreach \n [evaluate=\n as \snum using {int(mod(\n,2))}] in {1,2,...,#1} {
\draw[fill \snum,scale={pow(0.8,\n)}]
(A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0] (D0);
}
\end{tikzpicture}
}
\pic{2}
\pic{3}
\pic{4}
\pic{5}
\end{document}
具有四种样式的示例:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\newcommand{\pic}[1]{%
\begin{tikzpicture}[scale=3]
\tikzset{
fill 0/.style={fill=red},
fill 1/.style= {fill=blue},
fill 2/.style= {fill=green},
fill 3/.style= {fill=orange},
}
\coordinate (A0) at (0,0);
\foreach \n [evaluate=\n as \snum using {int(mod(\n,4))}] in {1,2,...,#1} {
\draw[fill \snum,scale={pow(0.8,\n)}]
(A0)--++(1,0)node(D0){}--++(0,-1)--++(-1,0)--++(0,1);
\coordinate (A0) at (D0);
\coordinate[below=30mm of A0] (D0);
}
\end{tikzpicture}
}
\begin{document}
\pic{2}\par
\pic{3}\par
\pic{4}\par
\pic{5}\par
\end{document}