1

I have drawn this:

enter image description here

With this code:

\documentclass{article}
\usepackage{tikz}
\tikzset{pics/message/.style={code={
\draw (0,0) rectangle (4,1);
\draw foreach \X in {1,2,3} {(\X,0) -- (\X,1)}; 
}}}
\begin{document}
\begin{tikzpicture}
\pic at (0,0) {message};
\end{tikzpicture}
\end{document}

Now i would like to fill each square with a number passed as parameters (for the moment it will be just 1..4 but not in order.

So i would like to have something like

\draw pic[0,0] {message=1/2/3/4};

As seen in this queston: TikZ 3.0---Multiple arguments for `pic` But i'm drawing each squares with a for loop and it would be interresting to keep this for loop in order to be able to draw a longer rectangle with more square and more parameters in the future. So something like:

\draw foreach \X in {1,2,3} {(\X,0) -- (\X,1) node[pos= 0.5, right] {param #X+1}}; 

While declaring the first label when drawing the rectangle with the #1 param to get something like:

enter image description here

If i call the function like that:

\draw pic[0,0] {message=1/2/3/4}; 
Kokodelo
  • 159

1 Answers1

2

I would probably do something like this:

\documentclass{article}
\usepackage{tikz}
\tikzset{pics/message/.style={code={
\draw (0,0) rectangle (4,1);
\draw foreach \X in {1,2,3} {(\X,0) -- (\X,1)}; 
\foreach \X [count=\Y,evaluate=\Y as \Z using {\Y-0.5}] in {#1}
{\node at (\Z,0.5) {\X};
\ifnum\Y=4
\breakforeach % make sure that the entries do not overshoot
\fi}
}}}
\begin{document}
\begin{tikzpicture}
\pic at (0,0) {message={1,A,F,2}};
\pic at (0,-2) {message={1,...,4}};
\pic at (0,-4) {message={3,...,14}};
\end{tikzpicture}
\end{document}

enter image description here

  • Could you explain me a bit this line \foreach \X [count=\Y,evaluate=\Y as \Z using {\Y-0.5}] in {#1} cause now i'm drawing these rectangle inside bigger one. And i'm calling the function of these rectangle to draw the ensemble and i would like to pass these parameters inside the 1sft function to give them later to the 2nd one who draw these little rectangle with labels – Kokodelo Oct 06 '18 at 14:48
  • @Kokodelo I am sorry, I do not understand the question. \foreach \X [count=\Y,evaluate=\Y as \Z using {\Y-0.5}] in {#1} loops of the argument #1, a list, where \Y is the count, 1,2,... and \Z is Y-0.5, which is used for the position. –  Oct 06 '18 at 15:35