[Tex/LaTex] Change background color in metapost

beamercolormetapost

I have a metapost diagram using colour that when displayed in normal latex (with a white background) works well. Now, I want to add the same diagram to a presentation done in Beamer (Warsaw theme) which has a blue background. The diagram does not look good at all — colour clash, too dark compared to the blue…

I have done this:

background:=white;
unfill (0,0)--(20u,0)--(20u,10u)--(0,10u)--cycle;

Which has the effect of drawing a white rectangle that then contains the diagram but it feel like a dirty hack.

How can I change the background of the diagram more elegantly?

Best Answer

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:

  1. Draw the image.
  2. Save the image in a picture variable.
  3. Measure the picture's bounding box.
  4. Draw the background.
  5. Re-draw the original image on top of the background.

Here's an example followed by some random notes:


beginfig(1);
  %
  % Draw random picture.
  %
  pair p,q;
  for i = 1 upto 20:
    p := (uniformdeviate 200, uniformdeviate 200);
    q := (uniformdeviate 200, uniformdeviate 200);
    draw p--q withpen pencircle scaled 2 withcolor red;
  endfor
  %
  % Solution starts here.
  %
  % Save picture in variable pic for later reference.
  picture pic;
  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.
  draw pic;
endfig;
end

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.

The 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 endfig.