\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{tikzpicture}
\draw[step=0.5cm,color=gray] (-1.5,-1.5) grid (1.5,1.5);
\matrix[matrix of nodes,nodes={inner sep=0pt,text width=.5cm,align=center,minimum height=.5cm}]{
6 & 9 & 7 & 2 & 6 & 4 & 5\\
2 & 6 & 9 & 7 & 4 & 6 & 5\\
2 & 4 & 6 & 9 & 7 & 5 & 6\\
2 & 4 & 5 & 6 & 9 & 7 & 6\\
2 & 4 & 5 & 6 & 6 & 9 & 7\\
2 & 4 & 5 & 6 & 6 & 7 & 9\\};
\end{tikzpicture}
我该如何修复这个网格?我想我已经尝试了所有方法,但它只穿过数字 :(
答案1
只需绘制每个单元格的轮廓,例如:every node/.style={draw}
\documentclass[12pt,a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
%\draw[step=0.5cm,color=gray] (-1.5,-1.5) grid (1.5,1.5);
\matrix[matrix of nodes,nodes={inner sep=0pt,text width=.5cm,align=center,minimum height=.5cm},every node/.style={draw}]{
6 & 9 & 7 & 2 & 6 & 4 & 5\\
2 & 6 & 9 & 7 & 4 & 6 & 5\\
2 & 4 & 6 & 9 & 7 & 5 & 6\\
2 & 4 & 5 & 6 & 9 & 7 & 6\\
2 & 4 & 5 & 6 & 6 & 9 & 7\\
2 & 4 & 5 & 6 & 6 & 7 & 9\\};
\end{tikzpicture}
\end{document}
答案2
@AndréC 的一个小变化回答:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of nodes,
nodes = {draw, minimum size=5mm,
anchor=center,
inner sep=0pt, outer sep=0pt},
column sep=-\pgflinewidth,
row sep=-\pgflinewidth,
]
{
6 & 9 & 7 & 2 & 6 & 4 & 5\\
2 & 6 & 9 & 7 & 4 & 6 & 5\\
2 & 4 & 6 & 9 & 7 & 5 & 6\\
2 & 4 & 5 & 6 & 9 & 7 & 6\\
2 & 4 & 5 & 6 & 6 & 9 & 7\\
2 & 4 & 5 & 6 & 6 & 7 & 9\\
};
\end{tikzpicture}
\end{document}
笔记:
- 单元格样式由 定义
nodes
(不需要单独的样式every nodes
) - 细胞之间的距离由
column sep=-\pgflinewidth,
row sep=-\pgflinewidth,