以下是如何进行此转换的示例...
假设您有一个图形,并且该图形包含一个带有句柄的轴对象hAxes
。使用功能ginput https://www.mathworks.com/help/matlab/ref/ginput.html将允许您选择轴内的点。得到一组等价的点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 https://www.mathworks.com/help/matlab/ref/ginput.html。请注意,如果坐标区对象嵌套在任何uipanel 对象 https://www.mathworks.com/help/matlab/ref/uipanel.html在图中,您还必须考虑面板位置。
Example:
为了说明上述代码的行为,这里有一个简洁的小示例。创建上述函数后,创建第三个函数:
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
当您将鼠标指针移到图形轴上时,您应该会看到在其后面绘制了一条红色星号,如下所示: