Whether the final render size is known is not really relevant. The
basic idea is to create a rectangle of the appropriate size and color
and placing it behind the diagram. The trick is how to compute the
appropriate size, but it can be done using the diagram's envelope.
There is actually already a function to do this in the darcs version
of diagrams-lib (
Diagrams.TwoD.Combinators.bg) but not in the released
version of diagrams-lib. Here's the code:
-- | Construct a bounding rectangle for an enveloped object, that is,
-- the smallest axis-aligned rectangle which encloses the object.
boundingRect :: ( Enveloped p, Transformable p, PathLike p, V p ~ R2
, Enveloped a, V a ~ R2
)
=> a -> p
boundingRect = (`boxFit` rect 1 1) . boundingBox
-- | \"Set the background color\" of a diagram. That is, place a
-- diagram atop a bounding rectangle of the given color.
bg :: (Renderable (Path R2) b) => Colour Double -> Diagram b R2 -> Diagram b R2
bg c d = d <> boundingRect d # lw 0 # fc c
-Brent