Here's a receipe for drawing an image whose dimensions aren't known in advance on a background that scales to the image's final bounding box:
- Draw the image.
- Save the image in a picture variable.
- Measure the picture's bounding box.
- Draw the background.
- Re-draw the original image on top of the background.
Here's an example followed by some random notes:
% Draw random picture.
for i = 1 upto 20:
p := (uniformdeviate 200, uniformdeviate 200);
q := (uniformdeviate 200, uniformdeviate 200);
draw p--q withpen pencircle scaled 2 withcolor red;
% Solution starts here.
% Save picture in variable pic for later reference.
pic := currentpicture;
% Clear currentpicture to avoid outputting the picture twice.
currentpicture := nullpicture;
% Fill a rectangle with pic's bounding box dimensions (plus
% bboxmargin) with desired background colour.
% interim bboxmargin := 0;
fill bbox pic withcolor blue;
% Draw original picture on top of background.
Saving an image in a picture variable can either be done by storing
currentpicture in a picture variable or via the
image command (see the MetaPost manual for more information). If the
currentpicture method is used, like in the example, make sure to clear
currentpicture before drawing the background. Otherwise the image is output twice, the first copy being hidden behind the background, bloating the output file.
bbox command returns a rectangular path corresponding to the bounding box of the picture argument plus a small amount determined by the internal variable
bboxmargin (2bp by default).
Internal variables can be modified locally to the current group using the
interim statement. That is, if you wrap an assignment to an internal variable in
begingroup ... endgroup; the variable's value is restored after the group. Note,
beginfig() just starts a group that ends at the corresponding