На самом деле вы можете сделать это, добавив 'WindowButtonMotionFcn'
< /a> к вашей фигуре (при условии, что больше ничего ее не использует), которая будет отображать линии перекрестия на ваших осях, когда ваша мышь находится над ней. Вот функция, которая создает такую функциональность для всех осей на фигуре:
function full_crosshair(hFigure)
% Find axes children:
hAxes = findall(hFigure, 'Type', 'axes');
% Get all axes limits:
xLimits = get(hAxes, 'XLim');
xLimits = vertcat(xLimits{:});
yLimits = get(hAxes, 'YLim');
yLimits = vertcat(yLimits{:});
% Create lines (not displayed yet due to NaNs) and listeners:
for iAxes = 1:numel(hAxes)
hHoriz(iAxes) = line(xLimits(iAxes, :), nan(1, 2), 'Parent', hAxes(iAxes));
hVert(iAxes) = line(nan(1, 2), yLimits(iAxes, :), 'Parent', hAxes(iAxes));
listenObj(iAxes) = addlistener(hAxes(iAxes), {'XLim', 'YLim'}, ...
'PostSet', @(~, ~) update_limits(iAxes));
end
% Set callback on the axes parent to the nested function below:
set(hFigure, 'WindowButtonMotionFcn', @show_lines);
function update_limits(axesIndex)
xLimits(axesIndex, :) = get(hAxes(axesIndex), 'XLim');
yLimits(axesIndex, :) = get(hAxes(axesIndex), 'YLim');
set(hHoriz(axesIndex), 'XData', xLimits(axesIndex, :));
set(hVert(axesIndex), 'YData', yLimits(axesIndex, :));
end
function show_lines(~, ~)
% Get current cursor positions in axes:
cursorPos = get(hAxes, 'CurrentPoint');
cursorPos = vertcat(cursorPos{:});
cursorPos = cursorPos(1:2:end, 1:2);
% Determine if the cursor is within an axes:
inAxes = (cursorPos(:, 1) >= xLimits(:, 1)) & ...
(cursorPos(:, 1) <= xLimits(:, 2)) & ...
(cursorPos(:, 2) >= yLimits(:, 1)) & ...
(cursorPos(:, 2) <= yLimits(:, 2));
% Update lines and cursor:
if any(inAxes) % Cursor within an axes
set(hFigure, 'Pointer', 'custom', 'PointerShapeCData', nan(16));
set(hHoriz(inAxes), {'YData'}, num2cell(cursorPos(inAxes, 2)*[1 1], 2));
set(hVert(inAxes), {'XData'}, num2cell(cursorPos(inAxes, 1)*[1 1], 2));
set(hHoriz(~inAxes), 'YData', nan(1, 2));
set(hVert(~inAxes), 'XData', nan(1, 2));
else % Cursor outside axes
set(hFigure, 'Pointer', 'arrow');
set(hHoriz, 'YData', nan(1, 2));
set(hVert, 'XData', nan(1, 2));
end
end
end
Если вы сделаете следующее:
full_crosshair(gcf);
Затем, когда вы перемещаете курсор по каждой оси на вашей фигуре, курсор исчезает, и вы видите, как появляются две линии, которые отслеживают положение мыши. Если какие-либо пределы осей изменяются, то прослушиватели событий в приведенном выше коде обнаружит и учтет это. Если оси добавляются или удаляются из фигуры, вам нужно будет снова вызвать full_crosshair
, чтобы соответствующим образом обновить 'WindowButtonMotionFcn'
.
Наконец, вы можете отключить его, просто очистив 'WindowButtonMotionFcn'
:
set(gcf, 'WindowButtonMotionFcn', []);
person
gnovice
schedule
15.11.2017