核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function drag_line(app, fig, sel_line)
sel_line.ButtonDownFcn = @bdfcn;
opx = 0;
function bdfcn(~, edata)
opx = edata.IntersectionPoint(1); % 鼠标点击位置在坐标轴中的x坐标
sel_line.Selected = 'on'; % 将拖动的线条设置为选中状态
app.UIFigure.WindowButtonMotionFcn = @wbmfcn; % 鼠标在窗口内移动时
app.UIFigure.WindowButtonUpFcn = @wbufcn; % 鼠标在窗口内弹起时
end
function wbmfcn(~,~)
cp = fig.CurrentPoint; % 当下鼠标所在的位置
dx = cp(1,1) - opx; % 鼠标移动的差值
newXData = sel_line.XData + dx;
xLimits = fig.XLim;
% 检查新的 XData 是否在范围内
if all(newXData >= xLimits(1)) && all(newXData <= xLimits(2))
sel_line.XData = newXData;
opx = cp(1,1); % 更新 opx
end
app.LocationEditField.Value = sel_line.XData(1);
end
function wbufcn(~,~)
app.UIFigure.WindowButtonMotionFcn = ''; % 窗口内按键移动回调
app.UIFigure.WindowButtonUpFcn = ''; % 窗口内按键弹起回调
sel_line.Selected = 'off';
end
end
% startupFcn
arrayfun(@(ax) disableDefaultInteractivity(ax),[app.UIAxes]);
xlim(app.UIAxes, [-10 10]);
drag_line(app, app.UIAxes, plot(app.UIAxes, [0 0], [0 1], 'LineWidth', 2));

运行效果

文字