![将 2 个 \foreach 循环合并为一个](https://linux22.com/image/400390/%E5%B0%86%202%20%E4%B8%AA%20%5Cforeach%20%E5%BE%AA%E7%8E%AF%E5%90%88%E5%B9%B6%E4%B8%BA%E4%B8%80%E4%B8%AA.png)
使用以下代码(来自这个问题) 使用 2 个 \foreach 循环绘制方框;并定义它们的起始位置 (yshift=.4cm 和 yshift=4.4cm)。我希望蓝色方框自动从红色方框结束的位置开始。
是否可以将它们组合成一个循环?
我的意思是使用一个 \foreach 循环来绘制下面 4 个红色框,然后继续绘制上面 2 个蓝色框。
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{verbatim}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{frame}[t]
\frametitle{}
\newsavebox{\recAr}
\savebox{\recAr}{%
\begin{tikzpicture}[scale=.6]
\draw [thick, black, fill=red] (0,0) rectangle +(1,1.24);
\end{tikzpicture}}
\newsavebox{\recAb}
\savebox{\recAb}{%
\begin{tikzpicture}[scale=.6]
\draw [thick, black, fill=blue!60!white] (0,0) rectangle +(1,1.24);
\end{tikzpicture}}
\begin{tikzpicture}[scale=.8, transform shape]
\draw [line width=.4mm, black, dashed] (0,5.8) -- +(0:11) (0,0) -- +(0:11) node [pos=.68] (A) {};
\foreach \X in {0,1,2,3}
{\node[yshift=.4cm] (y-\X) at (A|-0,\X){\usebox{\recAr}};}
\foreach \X in {0,1}
{\node[yshift=4.4cm] (y-\X) at (A|-0,\X){\usebox{\recAb}};}
\end{tikzpicture}
\end{frame}
\end{document}
答案1
仅使用部分循环并基于我的答案解决方案很简单:
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{verbatim}
\usepackage{tikz}
\usetikzlibrary{chains,
positioning}
\begin{document}
\begin{frame}[t, fragile]
\frametitle{}
\begin{tikzpicture}[
node distance = 1mm and 55mm,
start chain = going below,
box/.style = {draw, thick, fill=#1,
minimum width=6mm, minimum height=12mm,
inner sep=0pt, outer sep=0mm,
on chain}
]
\node (n1) [box=blue] {};
\node (n2) [box=blue] {};
\node (n3) [below=1ex of n2, % when you need additional space, otherwide omit this option
box=red] {}; %
\foreach \i in {4,5,6}
\node (n\i) [box=red] {};
\coordinate[left=of n1.north] (a); % for shift node to the right
\draw [line width=.4mm, dashed]
(a) -- ++ (11,0)
(a |- n6.south) -- ++ (11,0);
\end{tikzpicture}
\end{frame}
\end{document}
答案2
添加了Dunno's
根据 OP 要求制定解决方案的建议
您可以简单地循环变量:
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{verbatim}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{positioning}
\begin{document}
\begin{frame}[t]
\frametitle{}
\newsavebox{\recAr}
\savebox{\recAr}{%
\begin{tikzpicture}[scale=.6]
\draw [thick, black, fill=red] (0,0) rectangle +(1,1.24);
\end{tikzpicture}}
\newsavebox{\recAb}
\savebox{\recAb}{%
\begin{tikzpicture}[scale=.6]
\draw [thick, black, fill=blue!60!white] (0,0) rectangle +(1,1.24);
\end{tikzpicture}}
\begin{tikzpicture}[scale=.8, transform shape]
\draw [line width=.4mm, black, dashed] (0,5.8) -- +(0:11) (0,0) -- +(0:11) coordinate[pos=.68,alias=y-6] (A) {}; \path foreach \X [remember=\X as \LastX (initially 6)] in {5,4,...,0}{ node[above=1.5mm of y-\LastX,outer sep=0pt,inner sep=0pt] (y-\X) {\ifnum \X>3 \usebox{\recAb} \else \usebox{\recAr} \fi}};
\end{tikzpicture}
\end{frame}
\end{document}
要得到:
附言:我这样编写代码,只yshift
需要一个,从而使yshift
蓝色和红色框通用。