How can I program interactive panning into my app in MATLAB App Designer R2025b?

I have an app which implements a figure and a slider for zooming in and out on the figure. I have disabled the figure's toolbar to minimize conflict with the zoom slider, but now I have no way of panning the figure.
How can I program panning into my app so that I can zoom in to different locations of the figure?

 채택된 답변

There are two ways through which you can program interactive panning:
     1. Use a mouse callback to change the center of zoom to where the user clicks with their mouse. To do this, include these lines of code to enable the callback function in the app's startup function:
app.ZoomCenter = [(app.OrigXLim(1)+app.OrigXLim(2))/2, (app.OrigYLim(1)+app.OrigYLim(2))/2]; % OrigXLim and OrigYLim properties set in startup function
app.UIAxes.ButtonDownFcn = @(src, event)app.axesClicked();
Then implement a callback function that changes the center of zoom:
function axesClicked(app)
cp = app.UIAxes.CurrentPoint;
app.ZoomCenter = [cp(1,1), cp(1,2)];
end
     2. Use mouse callbacks to drag the figure in the same way as manual pan. This method requires three callback functions for when the mouse button is pushed, the mouse is moved, and the button is lifted. For example, include these lines in the app's startup function: 
app.UIFigure.WindowButtonDownFcn = @(src, event)app.startPan();
app.UIFigure.WindowButtonUpFcn = @(src, event)app.stopPan();
app.UIFigure.WindowButtonMotionFcn = @(src, event)app.doPan();
Then implement the three callback functions. For example:
function startPan(app)
% Only start pan if mouse is inside axes
cp = app.UIAxes.CurrentPoint;
x = cp(1,1);
y = cp(1,2);
xlim = app.UIAxes.XLim;
ylim = app.UIAxes.YLim;
if x >= xlim(1) && x <= xlim(2) && y >= ylim(1) && y <= ylim(2)
app.PanActive = true;
app.PanStartPoint = [x, y];
app.PanStartXLim = xlim;
app.PanStartYLim = ylim;
end
end
function doPan(app)
if app.PanActive
cp = app.UIAxes.CurrentPoint;
x = cp(1,1);
y = cp(1,2);
dx = x - app.PanStartPoint(1);
dy = y - app.PanStartPoint(2);
app.UIAxes.XLim = app.PanStartXLim - dx;
app.UIAxes.YLim = app.PanStartYLim - dy;
end
end
function stopPan(app)
app.PanActive = false;
end
Make sure to set the appropriate properties for each example (such as "OrigXLim", "OrigYLim", and "PanActive").
Please see MathWorks Documentation on Capturing Mouse Clicks for more information about mouse callbacks.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

제품

릴리스

R2025b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by