zoom image interactively maintaining a square zoom field
Show older comments
I'd like to use the + button with e.g. some control key, or some other trick, in order to zoom interactively on an image while maintaining a square 1:1 aspect ratio so the zoomed image is not distorted. Is there a way to do this?
4 Comments
Duncan Carlsmith
on 10 Apr 2023
Walter Roberson
on 10 Apr 2023
You can use the PostAction callback to set the zoom limits back to what would fit with square aspect ratio.
Or you could turn on zoom for the x axis, and use the PostAction callback to make the same change to the y limits.
Duncan Carlsmith
on 10 Apr 2023
Accepted Answer
More Answers (1)
Walter Roberson
on 10 Apr 2023
ax = gca;
hZoom = zoom(ax);
setAxesZoomConstraint(hZoom, 'x');
hZoom.ActionPostCallback = {@SquareZoom, ax.XLim(1), ax.YLim(1)};
function SquareZoom(hObj, evd, x0, y0)
ax = evd.Axes;
xwid = diff(ax.XLim);
ax.XLim = [x0, x0 + xwid];
ax.YLim = [y0, y0 + xwid];
end
This particular implementation anchors the x and y on the lower left corner of the axes limits as they exist at the time the action is started. Every time the callback is invoked, the limits will be re-anchored at that position.
There are, of course, other valid interpretations on what to do; for example you might have valid reason to want to support panning as well. Or at initialization time you might want to find the shorter of the current x and y and clamp the limits according to the shorter to keep the desired 1:1 ratio.
4 Comments
DGM
on 10 Apr 2023
I'm not sure how to set this up, but it just gives me an error.
Error using matlab.graphics.interaction.internal.zoom/setAxesZoomConstraint (line 7)
Input must be an axes handle.
Error in AT_sandbox (line 17)
setAxesZoomConstraint(hZoom, 'x');
Walter Roberson
on 10 Apr 2023
setAxesZoomConstraint(ax, 'x');
maybe.
Duncan Carlsmith
on 12 Apr 2023
Walter Roberson
on 12 Apr 2023
setAxesZoomConstraint is listed under "object functions" in https://www.mathworks.com/help/matlab/ref/matlab.graphics.interaction.internal.zoom.html
Categories
Find more on Data Exploration in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!