使用“foreach”制作棋盘

使用“foreach”制作棋盘

这两个图为何不同?

\documentclass{amsart}
\usepackage{amsmath}
\usepackage{amsfonts}

\usepackage{tikz}
\usetikzlibrary{calc,intersections}


\begin{document}


\begin{tikzpicture}

\foreach \y in {0,2,...,8}
{\foreach \x in {0,2,...,8}
{\draw[fill=black!50, xshift={(1/4)*sqrt(2)/2*\x*1cm}, yshift={(1/4)*sqrt(2)/2*\y*1cm}]
(0:{(1/4)*sqrt(2)/2}) -- (90:{(1/4)*sqrt(2)/2}) -- (180:{(1/4)*sqrt(2)/2}) -- (270:{(1/4)*sqrt(2)/2}) -- cycle;}
}

\draw ({-(1/4)*sqrt(2)/2},{-(1/4)*sqrt(2)/2}) rectangle ({(1/4)*9*sqrt(2)/2},{(1/4)*9*sqrt(2)/2});


\end{tikzpicture}


\begin{tikzpicture}[x=0.25cm, y=0.25cm]
\foreach \y in {0,2,...,8}
{\foreach \x in {0,2,...,8}
{\draw[fill=black!50, xshift={sqrt(2)/2*\x*1cm}, yshift={sqrt(2)/2*\y*1cm}] let \n1={sqrt(2)/2} in
(0:\n1) -- (90:\n1) -- (180:\n1) -- (270:\n1) -- cycle;}
}

\draw let \n1={sqrt(2)/2} in (-\n1,-\n1) rectangle ({9*\n1},{9*\n1});


\end{tikzpicture}


\end{document}

答案1

第二张图片有一个,[x=0.25cm, y=0.25cm]而第一张图片没有。

  • 这是不是相当于scale=0.25,您可能正在寻找。
  • 你告诉 TiZ 在第二张图片中明确表示xshift={sqrt(2)/2*\X*1cm}, yshift={sqrt(2)/2*\Y*1cm},因此它不关心单位向量的长度,而只是遵循您的指示。
  • 然而,这些单位向量的长度会对灰色矩形以及图片末尾的矩形的大小产生影响。
  • Z 对无量纲和有量纲坐标的处理方式非常不同,我们通常不关心这一点,因为我们选择的是标准单位向量。如果你选择不同的,你会感觉到这一点。对这些问题最清楚的解释可能是这个很好的答案,其中讨论的是圆形,而不是矩形,但定性论证是相同的。

\x顺便说一句,在我看来,如果你声明循环变量和\y某些使用 calc 语法的代码(该语法本身定义\x和),这不是一个好的做法。例如,请改用和 。\y\X\Y

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


\begin{document}

\paragraph{Original picture}~\par\noindent
\begin{tikzpicture}

\foreach \Y in {0,2,...,8}
{\foreach \X in {0,2,...,8}
{\draw[fill=black!50, xshift={(1/4)*sqrt(2)/2*\X*1cm}, yshift={(1/4)*sqrt(2)/2*\Y*1cm}]
(0:{(1/4)*sqrt(2)/2}) -- (90:{(1/4)*sqrt(2)/2}) -- (180:{(1/4)*sqrt(2)/2}) -- (270:{(1/4)*sqrt(2)/2}) -- cycle;}
}

\draw ({-(1/4)*sqrt(2)/2},{-(1/4)*sqrt(2)/2}) rectangle ({(1/4)*9*sqrt(2)/2},{(1/4)*9*sqrt(2)/2});
\end{tikzpicture}

\bigskip
\hrule
\bigskip

\paragraph{Second picture} This changes the unit vectors/units but the \texttt{xshift}s and
\texttt{yshift}s are specified explicitly, i.e.\ with explicit lengths, and do
\emph{not} get multiplied by the unit vectors:\par\noindent
\begin{tikzpicture}[x=0.25cm, y=0.25cm]
\foreach \Y in {0,2,...,8}
{\foreach \X in {0,2,...,8}
{\draw[fill=black!50, xshift={sqrt(2)/2*\X*1cm}, yshift={sqrt(2)/2*\Y*1cm}] 
let \n1={sqrt(2)/2} in 
(0:\n1) -- (90:\n1) -- (180:\n1) -- (270:\n1) -- cycle;}
}

\draw let \n1={sqrt(2)/2} in (-\n1,-\n1) rectangle ({9*\n1},{9*\n1});
\end{tikzpicture}

\bigskip
\hrule
\bigskip


\paragraph{Alternative} This is what you may be looking for:\par\noindent
\begin{tikzpicture}[scale=0.25]
\foreach \Y in {0,2,...,8}
{\foreach \X in {0,2,...,8}
{\draw[fill=black!50, xshift={sqrt(2)/2*\X*1cm}, yshift={sqrt(2)/2*\Y*1cm}] 
let \n1={sqrt(2)/2} in 
(0:\n1) -- (90:\n1) -- (180:\n1) -- (270:\n1) -- cycle;}
}

\draw let \n1={sqrt(2)/2} in (-\n1,-\n1) rectangle ({9*\n1},{9*\n1});
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容