[Tex/LaTex] A macro of drawing a rectangle with several parameters in TikZ

macrostikz-pgf

I draw a kind of box in TikZ very often, so I decide to make a macro, even though I have never done it before…

The aim is to draw a rectangle. 4 parameters (1, 7, 4, 8 in the figure) mean its bounds, which are displayed above and on the left hand of the rectangle. text is the text inside the rectangle. And I guess another 2 parameters are needed to determine the real width and height of the rectangle.

I have no clue about writing a macro, could anyone give a framework to start?

enter image description here

Best Answer

First and foremost, Peter Grill's first sentence is probably the most important piece of advice on this page (so far). First work out what you want normally, then wrap it up in a macro.

Given that this is part of a TikZ picture, you can do this using styles. This method is quite flexible. For example, here's one way to do your box:

\documentclass{standalone}
%\url{http://tex.stackexchange.com/q/27278/86}
\usepackage{tikz}
\usetikzlibrary{fit}

\tikzset{
  my funny rectangle/.style n args={4}{%
    rectangle,
    draw,
    fit={(#3,#1) (#4,#2)},
    append after command={\pgfextra{\let\mainnode=\tikzlastnode}
      node[above right] at (\mainnode.north west) {#3}%
      node[above left] at (\mainnode.north east) {#4}%
      node[below left] at (\mainnode.north west) {#1}%
      node[above left] at (\mainnode.south west) {#2}%
    },
  }
}

\begin{document}
\begin{tikzpicture}
\node[my funny rectangle={1}{7}{4}{8}] {text};
\end{tikzpicture}
\end{document}

An advantage of this method over a more normal TeX macro is that it is very easy to pass other options to the node, such as a colour or a fill or a pattern, simply by putting them in the usual place.

The code above works as follows. The fit library is used to ensure that the node contains the specified points. As it is a rectangle, we just need to include two opposite corners. Then the rest of the code puts the labels in. We use the append after command to put a node at the relevant places. The only snag is that we have to save the main node in a macro rather than using \tikzlastnode throughout (as that gets overwritten).

The above produces the following picture:

labelled rectangle

(Edit: Thanks to Jake for pointing out that five append after commands is a tad excessive.)

Related Question