【问题标题】:Matlab: convert global coordinates to figure coordinatesMatlab:将全局坐标转换为图形坐标
【发布时间】:2017-07-09 13:42:46
【问题描述】:

如果我通过

获得坐标
coords = get(0,'PointerLocation');

如何将它们转换为通过ginput 获得的积分?

即,我想从

获得相同的值
coords = get(0,'PointerLocation');
coords=someConversion(coords);

正如我打电话得到的那样

coords=ginput(1);

在图形内部单击与鼠标相同的位置是在前面的代码中。

【问题讨论】:

    标签: matlab coordinates


    【解决方案1】:

    以下是如何进行此转换的示例...

    假设您有一个图形,该图形包含一个带有句柄 hAxes 的坐标区对象。使用函数ginput 将允许您选择轴内的点。要从get(0, 'PointerLocation') 获得一组等效的点,它给出了与屏幕相关的坐标,您必须考虑图形位置、坐标轴位置、坐标轴宽度/高度和坐标轴限制。

    这样做很棘手,因为您希望位置度量采用相同的单位。如果您想以像素为单位计算所有内容,这意味着您必须将对象的'Units' 属性设置为'pixels',获取位置,然后将'Units' 属性设置回原来的状态。我通常会创建自己的函数get_in_units 来完成这部分:

    function value = get_in_units(hObject, propName, unitType)
    
      oldUnits = get(hObject, 'Units');  % Get the current units for hObject
      set(hObject, 'Units', unitType);   % Set the units to unitType
      value = get(hObject, propName);    % Get the propName property of hObject
      set(hObject, 'Units', oldUnits);   % Restore the previous units
    
    end
    

    使用上述函数,您可以创建另一个函数get_coords,它获取屏幕坐标并将它们转换为轴坐标:

    function coords = get_coords(hAxes)
    
      % Get the screen coordinates:
      coords = get_in_units(0, 'PointerLocation', 'pixels');
    
      % Get the figure position, axes position, and axes limits:
      hFigure = get(hAxes, 'Parent');
      figurePos = get_in_units(hFigure, 'Position', 'pixels');
      axesPos = get_in_units(hAxes, 'Position', 'pixels');
      axesLimits = [get(hAxes, 'XLim').' get(hAxes, 'YLim').'];
    
      % Compute an offset and scaling for coords:
      offset = figurePos(1:2)+axesPos(1:2);
      axesScale = diff(axesLimits)./axesPos(3:4);
    
      % Apply the offsets and scaling:
      coords = (coords-offset).*axesScale+axesLimits(1, :);
    
    end
    

    生成的coords 应该与使用ginput 得到的结果接近。请注意,如果轴对象嵌套在图中的任何 uipanel objects 中,您还必须考虑面板位置。


    示例:

    为了说明上述代码的行为,这里有一个简洁的小例子。创建上述函数后,创建第三个函数:

    function axes_coord_motion_fcn(src, event, hAxes)
    
      coords = get_coords(hAxes);               % Get the axes coordinates
      plot(hAxes, coords(1), coords(2), 'r*');  % Plot a red asterisk
    
    end
    

    然后运行以下代码:

    hFigure = figure;  % Create a figure window
    hAxes = axes;      % Create an axes in that figure
    axis([0 1 0 1]);   % Fix the axes limits to span from 0 to 1 for x and y
    hold on;           % Add new plots to the existing axes
    set(hFigure, 'WindowButtonMotionFcn', ...  % Set the WindowButtonMotionFcn so
        {@axes_coord_motion_fcn, hAxes});      %   that the given function is called
                                               %   for every mouse movement
    

    当您将鼠标指针移到图形轴上时,您应该会看到其后面绘制了一条红色星号轨迹,如下所示:

    【讨论】:

      【解决方案2】:

      您可以使用getpixelposition(gcf) 获取图形的位置,然后从 PointerLocation 中减去前 2 个元素(左下角的 x、y)以获得相对图形位置。

      对于更复杂的转换(例如,相对于某些内部面板或轴),您可能需要递归地获取子组件的相对位置。查看 pixelposition.m 或 moveptr.m 中的一些示例。

      【讨论】: