Set width of tikzpicture

fitpositioningtikz-pgf

I want to create the following tikzpicture:

enter image description here

I want the rectangle that fits around the example-image and nodes 2 and 3 to be, say, 0.6\textwidth wide.

Moreover, I want nodes 1 and 2 to be one adjacent to the other but centered inside this rectangle.

I came across this answer from 2012 where Peter Grill says that in his opinion it doesn't make sense to specify the height or width of a tikzpicture.

I agree with that to some extent but I don't want to wrap my tikzpicture inside a resizebox.

What I have now is this:

% !TEX TS-program = pdflatex
\documentclass{article}
\usepackage{tikz,lipsum}
\usetikzlibrary{positioning,fit}

\begin{document}
\lipsum[1]
\vskip 10pt

\noindent
\begin{tikzpicture}
\node(n0) [draw=black,outer sep=0pt] {node 1};
\node (n1) [below right = 1pt and 0pt of n0.south west,outer sep=0pt]  {\includegraphics[width=0.3\textwidth]{example-image}};
\node (n2) [below right = 10pt and 20pt of n1,draw=black] {node 2};
\node (n3) [right = 1pt of n2,draw=black] {node 3};
\node (n4) [below left = 0pt and 130pt of n3.south west,outer sep=0pt,draw=black] {node 4};

%draw a rectangle as the border
\node[draw, fit=(n1) (n3),inner sep=0pt](rect1) {};
\end{tikzpicture}
\end{document}

enter image description here

Any suggestion would be very welcome.

Best Answer

You can set the bounding box using \path then place items relative to its anchors. In this case, only the width matters until the end.

\documentclass{article}
\usepackage{tikz,lipsum}
\usetikzlibrary{positioning,fit}

\begin{document}
\lipsum[1]
\vskip 10pt

\noindent
\begin{tikzpicture}
\path (0,0) (0.6\textwidth,0);% set bounding box
\node(n0) [draw=black,outer sep=0pt, below right] at (current bounding box.west) {node 1};
\node (n1) [below right = 1pt and 0pt of n0.south west,outer sep=0pt]  {\includegraphics[width=0.3\textwidth]{example-image}};
\node (n2) [below left=1pt, draw=black] at (current bounding box.center |- n1.south) {node 2};
\node (n3) [right = 1pt of n2,draw=black] {node 3};
\coordinate (n4) at (current bounding box.south east);% set other corner

%draw a rectangle as the border
\node[draw, fit=(n1) (n4),inner sep=0pt](rect1) {};
\end{tikzpicture}
\end{document}

Slight simplification:

\documentclass{article}
\usepackage{tikz,lipsum}
\usetikzlibrary{positioning}

\begin{document}
\lipsum[1]
\vskip 10pt

\noindent
\begin{tikzpicture}
\path (0,0) (0.6\textwidth,0);% set bounding box
\node(n0) [draw=black,outer sep=0pt, below right] at (current bounding box.west) {node 1};
\node (n1) [below right = 1pt and 0pt of n0.south west,outer sep=0pt]  {\includegraphics[width=0.3\textwidth]{example-image}};
\node (n2) [below left=1pt, draw=black] at (current bounding box.center |- n1.south) {node 2};
\node (n3) [right = 1pt of n2,draw=black] {node 3};

%draw a rectangle as the border
\draw (n1.north west) rectangle (current bounding box.south east);
\end{tikzpicture}
\end{document}