我想使用pgfplots
或tikzpicture
绘制如下图所示的均匀网格。图中的网格大小为8×8
。我希望能够定义一个参数,使我能够绘制不同大小的网格,例如16×16
或32×32
。有人能帮我吗?
答案1
和tikz
\documentclass[tikz,border=5pt]{standalone}
\newcommand{\Grid}[2]{%
\def\maxX{#1}
\def\maxY{#2}
\begin{tikzpicture}
\draw[line width=1pt] (0,0) rectangle (\maxX,\maxY);
\foreach \x in {0,1,...,\maxX}{
\draw (\x,0) -- (\x,\maxY);
\draw[line width=1pt] (\maxX*0.5,0) -- (\maxX*0.5,\maxY);
\draw[line width=1pt,red] (\maxX*0.25,0) -- (\maxX*0.25,\maxY);
\draw[line width=1pt,red] (\maxX*0.75,0) -- (\maxX*0.75,\maxY);
}
%
\foreach \y in {0,1,...,\maxY}{
\draw (0,\y) -- (\maxX,\y);
\draw[line width=1pt] (0,\maxY*0.5) -- (\maxX,\maxY*0.5);
\draw[line width=1pt,red] (0,\maxY*0.25) -- (\maxX,\maxY*0.25);
\draw[line width=1pt,red] (0,\maxY*0.75) -- (\maxX,\maxY*0.75);
}
\end{tikzpicture}
}
\begin{document}
\Grid{8}{8}
\Grid{4}{4}
\Grid{16}{16}
\Grid{32}{32}
\end{document}
答案2
这是一个使用grid
...的解决方案
\documentclass[tikz,margin=1mm]{standalone}
\newcommand\mygrid[1]{
\begin{tikzpicture}
\draw[black,line width=1pt] (0,0) grid[step=1] (#1,#1);
\draw[red,line width=1pt] (0,0) grid[step=2] (#1,#1);
\draw[black,line width=4pt] (0,0) grid[step=4] (#1,#1);
\draw[black,line width=4pt] (0,0) rectangle (#1,#1);
\end{tikzpicture}
}
\begin{document}
\mygrid{4}
\mygrid{8}
\mygrid{16}
\mygrid{32}
\end{document}