简体   繁体   English

如何使用MATLAB GUIDE确定鼠标是否在轴上

[英]How to determine if mouse is over axes using MATLAB GUIDE

I know this question has been asked before, but I can't find any good answers. 我知道这个问题以前曾被问过,但我找不到任何好的答案。 I keep stumbling upon WindowButtonMotionFcn , but I don't really understand how to use it. 我一直在WindowButtonMotionFcn地使用WindowButtonMotionFcn ,但是我不太了解如何使用它。 In my program I want to be able to click and store coordinates ONLY when the user is above a certain axes, so that the normal mouse appears for the rest of the GUI and they can play with other buttons. 在我的程序中,我希望仅当用户在特定轴上方时才能单击并存储坐标,以便普通鼠标出现在GUI的其余部分,并且它们可以与其他按钮一起玩。 Thanks for any insight. 感谢您的见解。

I would recommend not using WindowButtonMotionFcn and instead use the ButtonDownFcn of your axes object. 我建议不要使用WindowButtonMotionFcn ,而应使用轴对象的ButtonDownFcn This way MATLAB takes care of your hit detection for you. 这样,MATLAB会为您处理命中检测。

For example: 例如:

function testcode()
h.myfig = figure;
h.myaxes = axes( ...
    'Parent', h.myfig, ...
    'Units', 'Normalized', ...
    'Position', [0.5 0.1 0.4 0.8], ...
    'ButtonDownFcn', @myclick ...
    );
end

function myclick(~, eventdata)
fprintf('X: %f Y: %f Z: %f\n', eventdata.IntersectionPoint);
% Insert data capture & storage here
end

Prints your coordinate every time you click inside the axes but does nothing when you click anywhere else. 每次在轴内单击时,都会打印坐标,但在其他位置单击时,则不执行任何操作。

EDIT: 编辑:

Since this is a GUIDE GUI the easiest approach is to utilize getappdata to pass data around the GUI. 由于这是GUIDE GUI,所以最简单的方法是利用getappdata在GUI周围传递数据。 To start, you need to modify your GUI_OpeningFcn to something like the following: 首先,您需要将GUI_OpeningFcn修改为以下内容:

function testgui_OpeningFcn(hObject, eventdata, handles, varargin)

% Choose default command line output for testgui
handles.output = hObject;

% Initialize axes click behavior and data storage
set(handles.axes1, 'ButtonDownFcn', {@clickdisplay, handles}); % Set the axes click handling to the clickdisplay function and pass the handles
mydata.clickcoordinates = []; % Initialize data array
setappdata(handles.figure1, 'mydata', mydata); % Save data array to main figure

% Update handles structure
guidata(hObject, handles);

And then add a click handling function elsewhere in your GUI: 然后在GUI的其他位置添加点击处理功能:

function clickdisplay(~, eventdata, handles)
mydata = getappdata(handles.figure1, 'mydata'); % Pull data from main figure
mydata.clickcoordinates = vertcat(mydata.clickcoordinates, eventdata.IntersectionPoint); % Add coordinates onto the end of existing array
setappdata(handles.figure1, 'mydata', mydata); % Save data back to main figure

You can then pull the array into any other callback using the same getappdata call. 然后,您可以使用相同的getappdata调用将数组拉入任何其他回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM