Matlab:获取图中点击的坐标但保持按钮回调

时间:2011-12-13 07:43:41

标签: matlab input callback click

我需要一个函数,它给出了我的图形窗口中点击的坐标和点击的鼠标按钮(左,中,右或按键),但我仍然想使用uicontrol() - 按钮。我目前正在使用ginput()工作正常,但按钮回调函数未执行,因此我认为ginput()会覆盖它们:( 非常感谢!

编辑:来自matt(第二个花盆)的“编辑”代码执行此操作,但只是不提供单击WHICH按钮的功能: http://www.mathworks.com/matlabcentral/answers/7528-ginput-in-a-gui :(

修改 最后我自己弄清楚了。我希望你喜欢它。我更改了matt的原始代码:

function varargout = ginput_ax(ha,n)
if nargin<2
    n=1;
end
k = 0;
button = 0;
xy = zeros(n,2);
hf = get(ha,'parent');
figure(hf);
set(hf,'WindowButtonMotionFcn',@changepointer)
set(ha,'ButtonDownFcn',@getpoints)
hp = get(ha,'children');
ht = get(hp,'hittest');
set(hp,'hittest','off')
axlim = get(ha,'Position');
fglim = get(hf,'Position');
x1 = axlim(1)*fglim(3) + fglim(1);
x2 = (axlim(1)+axlim(3))*fglim(3) + fglim(1);
y1 = axlim(2)*fglim(4) + fglim(2);
y2 = (axlim(2)+axlim(4))*fglim(4) + fglim(2);
waitfor(hf,'WindowButtonMotionFcn',[])
if iscell(ht)
    for jj=1:length(ht)
        set(hp(jj),'hittest',ht{jj})
    end
else
    set(hp,'hittest',ht)
end

% Mouse-Button recognition...
if(strcmp(button, 'normal'))
    button = 1; % left
elseif(strcmp(button, 'extend'))
    button = 2; % right
elseif(strcmp(button, 'alt'))
    button = 3; % middle
else
    button = 4; % double click any mousebutton
end

if nargout==3 
    varargout{1} = xy(:,1);
    varargout{2} = xy(:,2);
    varargout{3} = button;
elseif nargout==2
    varargout{1} = xy(:,1);
    varargout{2} = xy(:,2);
else
    varargout{1} = xy;
end
    function changepointer(~,~)
        pntr = get(0,'PointerLocation');
        if pntr(1)>x1 && pntr(1)<x2 && pntr(2)>y1 && pntr(2)<y2
            set(hf,'Pointer','crosshair')
        else
            set(hf,'Pointer','arrow')
        end
    end
    function getpoints(src,evnt)
        cp = get(src,'CurrentPoint');
        button = get(hf, 'SelectionType');
        k = k+1;
        xy(k,:) = cp(1,1:2);
        if k==n
            set(hf,'Pointer','arrow')
            set(hf,'WindowButtonMotionFcn',[])
            set(ha,'ButtonDownFcn',[])
        end
    end
end

只需将其复制到“ginput_ax.m”等新文件中,然后通过

调用即可
figure
ginput_ax(gca, N)

N是捕获的点数!甚至比ginput更好,因为uicontrol按钮工作,双击识别并且十字准线指针仅显示在实际绘图中,而不是在图窗口中的绘图周围的灰色边框上:)希望你喜欢它!

1 个答案:

答案 0 :(得分:1)

我自己找到了一个好的工作方案,它甚至比ginput更好,因为十字准线只显示在实际的图中(因此在轴内)。请参阅上面的编辑!