I would like to have array with square cells and fill cells with colors. There is done implementation of table with square cells by W. Robertson http://www.tug.org/pracjourn/2005-2/robertson/robertson.pdf :
\newlength\celldim \newlength\fontheight \newlength\extraheight
\newcounter{sqcolumns}
\newcolumntype{S}{ @{}
>{\centering \rule[-0.5\extraheight]{0pt}{\fontheight + \extraheight}}
p{\celldim} @{} }
\newcolumntype{Z}{ @{} >{\centering} p{\celldim} @{} }
\newenvironment{squarecells}[1]
{\setlength\celldim{2em}%
\settoheight\fontheight{A}%
\setlength\extraheight{\celldim - \fontheight}%
\setcounter{sqcolumns}{#1 - 1}%
\begin{tabular}{|S|*{\value{sqcolumns}}{Z|}}\hline}
% squarecells tabular goes here
{\end{tabular}}
\newcommand\nl{\tabularnewline\hline}
So I write:
\documentclass[a4paper,12pt]{report}
\usepackage[MeX]{polski}
\usepackage[utf8]{inputenc}
\usepackage[table]{xcolor}
\usepackage{array}
\usepackage{calc}
\newlength\celldim \newlength\fontheight \newlength\extraheight
\newcounter{sqcolumns}
\newcolumntype{S}{ @{}
>{\centering \rule[-0.5\extraheight]{0pt}{\fontheight + \extraheight}}
p{\celldim} @{} }
\newcolumntype{Z}{ @{} >{\centering} p{\celldim} @{} }
\newenvironment{squarecells}[1]
{\setlength\celldim{4em}%
\settoheight\fontheight{A}%
\setlength\extraheight{\celldim - \fontheight}%
\setcounter{sqcolumns}{#1 - 1}%
\begin{tabular}{|S|*{\value{sqcolumns}}{Z|}}\hline}
% squarecells tabular goes here
{\end{tabular}}
\newcommand\nl{\tabularnewline\hline}
\begin{document}
\begin{squarecells}{4}
\cellcolor{red}16 & 3 & 2 & 13 \nl
5 & 10 & 11 & 8 \nl
9 & 6 + 2 & 7 & 12 \nl
4 & 15 & 14 & 1 \nl
\end{squarecells}
\end{document}
Output is:
Cell is filled with red color a little more than it should be. Question is, how to properly fill cell with color? Or maybe is there some other good solution to create table with square cells?
Best Answer
If you're not set on the
array
approach and would be okay with explicitly specifying the size of the squares, you could use TikZ for this. Based on the answer to the question TikZ matrix as a replacement for tabular, you could define astyle
that adjusts a TikZmatrix
to have all the cells join each other and have identical heights and widths:To adjust the size of the elements, use
square matrix=<length>
. To fill elements with different colours, use|[fill=<colour>]|
in the cell you want to adjust.