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?
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:
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 theappend 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:
(Edit: Thanks to Jake for pointing out that five
append after command
s is a tad excessive.)