[Tex/LaTex] Centering a TikZ picture around an area

diagramshorizontal alignmenttikz-pgfvertical alignment

I often find myself in the following situation: A tikzpicture of mine consists of a main area and some outer material like text labels which are hardly symmetric around the main area. If such a picture is centered the main area is not in the center which often looks not very nice.

Not nicely centered

I would like to state which (rectangle) area of the picture should be placed in the center. This should be best possible with either a macro or an option (TikZ setting) where I can state the lower-left and upper-right coordinates of the main area.

Nicely centered

I know I could use use as bounding box when drawing the main area so that everything is not taken as part of the official picture, but this is often not useful. If the picture is converted to a PDF image using preview or standalone the outer areas would be clipped. Also the main area might be quite complicated and not easily put into a single scope.

So my idea is to have some code which measure the existing bounding box around the given main area and expands the bounding box by adding some white space so that this area is in the center. Horizontal centering is the main target, but vertical centering might also be possible.

An example would be:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\hrule

\begin{figure}
    \centering
\begin{tikzpicture}[<some key>={1,0}{6,5}]
 \draw (1,0) rectangle (6,5);
 \draw (1,0) -- (6,5);
 \node [left] at (0,2.5) {Text};
 \orsomemacro{1,0}{6,5}
\end{tikzpicture}
\caption{Caption}
\end{figure}

\end{document}

I personally would prefer a TikZ key/style, but an alternative macro provided in addition would be a bonus. Special care must be taken because the coordinates are not yet defined at the beginning of the picture. The coordinate argument should allow any TikZ coordinate including calc expressions with internal ( ). The coordinates could be given using { } instead of ( ) to simply the parsing. However, normal TikZ syntax is of course preferred.

I (of course) already coded something like this and will post it as an answer after a while. I'm happy to see other solutions and will be happy to give away a bounty for the best one.

Best Answer

Here my first attempt. It defines a xcenter around={lower left}{upper right} key which should be used in the optional argument of the tikzpicture, e.g. \begin{tikzpicture}[xcenter around={1,0}{6,5}].

\usetikzlibrary{calc}

\tikzset{xcenter around/.style 2 args={execute at end picture={%
  \useasboundingbox let \p0 = (current bounding box.south west), \p1 = (current bounding box.north east),
                        \p2 = (#1), \p3 = (#2)
                    in
        ({min(\x2 + \x3 - \x1,\x0)},\y0) rectangle ({max(\x3 + \x2 - \x0,\x1)},\y1);
}}}

I'm working on an extended version which adds more functionality.