# How to constrain text to a rectangle in tikzpicture?

I have a list of rectangular blocks that have a text, color, and size (y start, y size, x start, and x size). I want the text to be in the center of the rectangle, such that it does not go outside of rectangle.

Currently I am using \\ in text to make sure the text fits, but this requires too much playing around, I would prefer them to fit automatically. Here is my current code:

\foreach \text/\color/\ystart/\ysize/\xstart/\xsize in \rectangularblocks {
\filldraw[fill=\color] (\xstart, \ystart) rectangle (\xstart+\xsize, \ystart+\ysize);
\draw (\xstart+\xsize/2, \ystart+\ysize/2) node[align=center] {\text};
}

Based on other answers I saw, this can be done in two ways:

1. By turning on wrapping and bounding the text to the size of the rectangle.
2. By scaling the text to fit in rectangle.

But I fail to come up with code that can do either (and keeping the text in the center of my rectangle). I would prefer #1 as it means I do not have to play around with \\ in my text.

-
So you want to restrict it both to the X and Y size, do I see that right? So wrap and scale if required? – Martin Scharrer Jul 14 '11 at 14:05

I would set it with the requested width and then scale it down if needed. Doing this manually is probably easier than trying to integrate it with the TikZ settings.

\node {%
\setkeys{Gin}{keepaspectratio}%
\resizebox*{\xsize}{\ysize}{%
\begin{minipage}{\xsize}%
\centering
\text
\end{minipage}%
}%
}

If you are willing to do some automatic calculation and don't mind if the text is processed multiple times, then you could do it also more sophisticated to figure out the perfect wrapping vs. scaling ratio.

-
Note: The next version of adjustbox will include a \maxsizebox macro which is like \resizebox but only resizes something if it is to large. – Martin Scharrer Jul 14 '11 at 14:55
Additional things I had to do to get this working: use \begin{center}, add units of cm, scale the sizes inside of \resizebox by my tikzpicture scale factor, change to use \draw (...) node { } rather than \node so I can position it. – earlNameless Jul 14 '11 at 15:44
@earlNameless: You can use \node at (x,y) {...}; to position it. The sizes given to \resizebox and minibox must be of course full lengths, not just factors. \centering works fine for me. Note the the center environment adds vertical spacing which might not wanted. – Martin Scharrer Jul 14 '11 at 16:12