Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
    
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

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
1  
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
2  
@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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.