7

How to alter the following code, to have the tikzpicture to have the exact width and height of the minipage containing it (without changing the literal coordinates of course :))?

\begin{minipage}{2cm}

\begin{tikzpicture}

\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);

\end{tikzpicture}

\end{minipage}
4
  • 1
    The height of a minipage isn't fixed, but you can use \resizebox{} from the graphics package set set either or both. Commented May 5, 2014 at 22:27
  • 1
    \begin{tikzpicture}[x=0.5cm,y=0.5cm] ???
    – user11232
    Commented May 5, 2014 at 22:28
  • \resizebox{2cm}{2cm}{...} works. Thank you John Kormylo :) [Btw. I do now think it's a stupid question ... in this example it works fine ... it's a simplified version of what I'm trying to do and I realized just now the reason this didnt work in my code is related to another thing ... Sorry!]
    – MCH
    Commented May 5, 2014 at 22:35
  • Related Question/Duplicate?: How to scale a tikzpicture to \textwidth. Commented Oct 28, 2014 at 22:57

1 Answer 1

7

While the \resizebox will scale the picture, it will also scale the text in it. This is usually not desired.

Below, I defined \MyResizeBox which measures the width of the picture and then produces the images with an appropriate scale, so that only the graphics are scaled, yet the text remains the same size

enter image description here

Notes:

  • I added a \fbox so that we could see the minipage boundary.
  • The tabluar is only so that I could obtain a nice image to post here -- It is not related to the the solution.
  • The tikzpicture was packaged into a macro to eliminate repeating the code.

Code:

\documentclass{article}
\usepackage{tikz}
\usepackage{graphicx}

\newcommand*{\MyScale}{1}%
\newcommand*{\MyPicture}{%
\begin{tikzpicture}[scale=\MyScale]
    \draw [ultra thick, blue] (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
    \node at (2,2) {Some text};
\end{tikzpicture}%
}%

\newcommand*{\MyResizeBox}[2]{%
    \sbox0{#2}%
    \pgfmathsetmacro{\MyScale}{#1/\wd0}%
    #2%
}%

\begin{document}

\begin{tabular}{p{5.0cm} p{4.0cm} p{4.0cm}}
Original & \verb|\resizebox| & \verb|\MyResizeBox| \\

\fbox{%
\begin{minipage}{3cm}
    \MyPicture%
\end{minipage}%
}%
&
\fbox{%
\begin{minipage}{3cm}
    \resizebox{3.0cm}{3.0cm}{\MyPicture}%
\end{minipage}%
}%
&
\fbox{%
\begin{minipage}{3cm}
    \MyResizeBox{3.0cm}{\MyPicture}%
\end{minipage}%
} \\%
\end{tabular}
\end{document}
1
  • Haha, did u read my mind? Your solution is exactly what I needed ...
    – MCH
    Commented May 7, 2014 at 18:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .