3

I would like to write a macro background which takes 2 arguments and each argument can contain a list of numbers separated by ,, such that the following code draws two boxes with borders inside.

\usepackage{tikz}
\begin{document}
\begin{center}
  \begin{tikzpicture}[]
    % a box has 3 rows and 4 columns, 
    % the heights of the rows are respectively 1, 2 and 1;
    % the widths of the columns are respectively 1, 2, 2 and 1: 
    \background{1,2,1}{1,2,2,1} 
  \end{tikzpicture}
\end{center}
\begin{center}
  \begin{tikzpicture}[]
    % a box has 4 rows and 3 columns, 
    % the heights of the rows are respectively 1, 2, 3 and 1;
    % the widths of the columns are respectively 1, 2 and 1:
    \background{1,2,3,1}{1,2,1}
  \end{tikzpicture}
\end{center}
\end{document}

Drawing borders is not a problem, but the difficulty is how to go through the numbers in each argument of background, whose number is various.

Does anyone know how to do that?

Edit 1: the first box expected:

enter image description here

the second box expected:

enter image description here

SoftTimur
  • 19,767

1 Answers1

1

You can use \foreach to do the job. Below I'm modifying @percusse's code in this answer to adjust cell dimensions.

MWE

\documentclass{article}
\usepackage{tikz,etoolbox}
\usetikzlibrary{matrix}

\newcommand\background[2]{
  \let\mymatrixcontent\empty
  \newcommand{\row}{%
    \foreach \j in {#1}{
      \foreach \i in {#2} {%
        \begingroup\edef\x{\endgroup
           \noexpand\gappto\noexpand\mymatrixcontent{|[minimum height=\j cm,minimum width=\i cm,draw]| \&}}\x
        }%
      \gappto\mymatrixcontent{\\}%
    }
  }
  \row
  \matrix[matrix of nodes,ampersand replacement=\&,row sep=-\pgflinewidth,column sep=-\pgflinewidth]{
    \mymatrixcontent
  };
}

\begin{document}
\begin{center}
  \begin{tikzpicture}[]
    % a box has 3 rows and 4 columns, 
    % the heights of the rows are respectively 1, 2 and 1;
    % the widths of the columns are respectively 1, 2, 2 and 1: 
    \background{1,2,1}{1,2,2,1} 
  \end{tikzpicture}
  \begin{tikzpicture}[]
    % a box has 4 rows and 3 columns, 
    % the heights of the rows are respectively 1, 2, 3 and 1;
    % the widths of the columns are respectively 1, 2 and 1:
    \background{1,2,3,1}{1,2,1}
  \end{tikzpicture}
\end{center}
\end{document}

Output

enter image description here

Herr K.
  • 17,946
  • 4
  • 61
  • 118