trying to get current point on a patch in the axes

Hi I wrote the next code:
set(worldAxes,'ButtonDownFcn',@mouseCB5);
% using this line I call the next function (worldAxes is the name i gave to my axes
function [] = mouseCB5 (hObject,event)
XY1 = get(hObject,'CurrentPoint');
xPosition = XY1(1,1);
yPosition = XY1(1,2);
fprintf('x=%f Y=%f \n',xPosition,yPosition)
end
what I want is whenever i press the left button of the mouse somewhere in the axes area, I will get the position of the cursor in the axes.
when the cursor is somewhere on an empty place in the axes area, every thing is fine.
however ,once the cursor is over a patch object (a square) I do not get the current position
it just wouldn't work

Answers (1)

Ehud - I think that what you want to do is to attach this callback to both your axes (like you are doing now) and to the patch object. Suppose we have the following code to create the patch
figure;
t = 0:pi/5:2*pi;
hPatch = patch(sin(t),cos(t),'y');
axis equal;
which will give us a yellow decagon. As before we assign the callback to the axes and (now) to the patch object too
set(gca,'ButtonDownFcn',@mouseCB5);
set(hPatch,'ButtonDownFcn',@mouseCB5);
In the above, we use gca to get the handle to the current axes. Now if we were to run your code, it would work when we click outside of the patch but will crash when we click within it because a patch object doesn't have a current point property like the axes. So we have to adjust your callback to handle whether you are clicking within a patch object or the axes
function [] = mouseCB5 (hObject,event)
% get the type of object
type = get(hObject,'Type');
if strcmpi(type,'axes')
XY1 = get(hObject,'CurrentPoint');
elseif strcmpi(type,'patch')
XY1 = get(get(hObject,'Parent'),'CurrentPoint');
else
fprintf('unhandled object type!\n');
return;
end
xPosition = XY1(1,1);
yPosition = XY1(1,2);
fprintf('x=%f Y=%f \n',xPosition,yPosition)
end
Note how we get the type of the object being clicked. If it is the axes then we do as before and get the current point. If the type of object being clicked is the patch object, then we get its parent (which is the axes) and grab the parent/axes current point.
Try the above and see what happens!

1 Comment

Works, perfect! Best solution if you want to avoid resorting to ginput or the data cursors

Sign in to comment.

Asked:

on 17 Jan 2015

Commented:

on 24 Oct 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!