Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ExploreGraphics with maintaining AspectRatio
ExploreGraphics::usage =
"Pass a Graphics object to explore it by zooming and panning with \
left and right mouse buttons respectively. Left click once to reset \
view.";
OptAxesRedraw::usage =
"Option for ExploreGraphics to specify redrawing of axes. Default \
True.";
Options[ExploreGraphics] = {OptAxesRedraw -> True};
ExploreGraphics[graph_Graphics, opts : OptionsPattern[]] :=
With[{gr = First[graph],
opt = DeleteCases[Options[graph],
PlotRange -> _ | AspectRatio -> _ | AxesOrigin -> _],
plr = PlotRange /. AbsoluteOptions[graph, PlotRange],
ar = AspectRatio /. AbsoluteOptions[graph, AspectRatio],
ao = AbsoluteOptions[AxesOrigin],
rectangle = {Dashing[Small],
Line[{#1, {First[#2], Last[#1]}, #2, {First[#1],
Last[#2]}, #1}]} &,
optAxesRedraw = OptionValue[OptAxesRedraw]},
DynamicModule[{dragging = False, first, second, boxSize, minPos,
rx1, rx2, ry1, ry2, range = plr}, {{rx1, rx2}, {ry1, ry2}} =
plr;
Panel@
EventHandler[
Dynamic@Graphics[
If[dragging, {gr, rectangle[first, second]}, gr],
PlotRange -> Dynamic@range, AspectRatio -> ar,
AxesOrigin ->
If[optAxesRedraw, Dynamic@Mean[range\[Transpose]], ao],
Sequence @@ opt], {{"MouseDown",
1} :> (first = MousePosition["Graphics"]), {"MouseDragged",
1} :> (dragging = True;
boxSize = MousePosition["Graphics"] - first;
minPos = Min[Abs[boxSize]];
second =
first + {minPos, minPos}*RealSign[boxSize]), {"MouseUp",
1} :> If[dragging, dragging = False;
range = {{rx1, rx2}, {ry1, ry2}} = Transpose@{first, second},
range = {{rx1, rx2}, {ry1, ry2}} = plr], {"MouseDown",
2} :> (first = {sx1, sy1} =
MousePosition["Graphics"]), {"MouseDragged",
2} :> (second = {sx2, sy2} = MousePosition["Graphics"];
rx1 = rx1 - (sx2 - sx1);
rx2 = rx2 - (sx2 - sx1);
ry1 = ry1 - (sy2 - sy1);
ry2 = ry2 - (sy2 - sy1);
range = {{rx1, rx2}, {ry1, ry2}})}]]];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.