# Collecting tikZ drawings in a box

Please is it possible to collect tikz picture in the following way? I get \box40=\hbox(0.0+0.0)x0.0 []. I would even prefer a \vbox, but I get a worse outcome.

\makeatletter
\newbox\tempbox
\newbox\mainbox
\def\collecttikzpicture{\@testopt\@collecttikzpicture{}}
\def\@collecttikzpicture[#1]{%
\global\setbox\tempbox=\hbox\bgroup\begin{tikzpicture}[#1]%
}
\def\endcollecttikzpicture{%
\end{tikzpicture}\egroup
\setbox\mainbox=\hbox{\unhbox\mainbox\unhbox\tempbox}%
}

\begin{collecttikzpicture}[remember picture,overlay]
\draw [cyan,fill=yellow]
(0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\showbox\mainbox
\makeatother

-
The code for \endcollect... runs inside the group for your collecttikzpicture environment so as you made a local setting of \mainbox it is not set outside the group. Perhaps you just need \global but I'm note sure what teh code is intended to do. –  David Carlisle Jun 12 '12 at 23:00

You need to collect your main box outside the environment group:

\def\endcollecttikzpicture{%
\end{tikzpicture}\egroup
\aftergroup\collectbox
}

\def\collectbox{\setbox\mainbox=\hbox{\unhbox\mainbox\unhbox\tempbox}}


Note, that this makes the \mainbox contain the picture, it still has zero size because of the overlay option passed to the tikzpicture. If you remove that the box attains the natural dimensions of the square.

As you said you would prefer a vbox:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\makeatletter
\newbox\tempbox
\newbox\mainbox
\def\collecttikzpicture{\@testopt\@collecttikzpicture{}}
\def\@collecttikzpicture[#1]{%
\global\setbox\tempbox=\hbox\bgroup\begin{tikzpicture}[#1]%
}
\def\endcollecttikzpicture{%
\end{tikzpicture}\egroup
\aftergroup\collectbox
}

\def\collectbox{\setbox\mainbox=\vbox{\unvbox\mainbox\box\tempbox}}
\makeatother

\begin{collecttikzpicture}[remember picture]
\draw [cyan,fill=yellow]
(0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\begin{collecttikzpicture}[remember picture]
\draw [cyan,fill=blue]
(0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

\begin{collecttikzpicture}[remember picture]
\draw [cyan,fill=green]
(0cm,0cm)--(2cm,0cm)--(2cm,-2cm)--(0cm,-2cm)--cycle;
\end{collecttikzpicture}

[[[\box\mainbox]]]

\end{document}

-
I needed it for the xbackground package at tex.stackexchange.com/questions/59283/…. Now I can replace the collector command with a box. The box will be faster: once evaluated, it can be inserted on desired pages. –  Ahmed Musa Jun 13 '12 at 1:13
What is explanation that \setbox\mainbox=\vbox{\unvbox\mainbox\unhbox\tempbox} is impossible? Is it due to incompatible boxes or \@nodocument? –  Ahmed Musa Jun 13 '12 at 1:41
yes if you previously collected mainbox as a vbox you can't unhbox it. What were you trying to do? –  David Carlisle Jun 13 '12 at 8:18