A minor addition to the other answers.
As it is recently uncovered by Carl Woll, ImageSize
accepts undocumented form
ImageSize -> Automatic -> {width, height}
which allows you to specify the width and height of the plot range directly.
This option has higher precedence than AspectRatio
:
gr = Graphics[{Lighter@Blue, Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},
ImageSize -> Automatic -> {300, 100}, AspectRatio -> 1, Frame -> True,
Background -> GrayLevel[0.8], FrameStyle -> Opacity[0]]
ImageCrop[%] // ImageDimensions
{300, 100}
It can be used in combination with AspectRatio
:
Graphics[{Lighter@Blue, Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]]},
ImageSize -> Automatic -> {Automatic, 100}, AspectRatio -> 1/3, Frame -> True,
Background -> GrayLevel[0.8], FrameStyle -> Opacity[0]]
ImageCrop[%] // ImageDimensions
{300, 100}
The only (but crucial!) drawback is that this undocumented form doesn't play well when Graphics
is wrapped by Inset
:
Graphics[{Inset[gr, {0, 0}, {0, 0}, Automatic]}, Background -> LightGreen,
AspectRatio -> 1/3]
A workaround is to wrap Graphics
by Pane
, Framed
, Text
or ExpressionCell
:
Graphics[{Inset[Text[gr]]}, Background -> LightGreen, AspectRatio -> 1/3,
ImagePadding -> None, ImageMargins -> 0, ImageSize -> {400, 150}]
ImageCrop@ImageCrop@% // ImageDimensions
{300, 100}