MATLAB: Hovering on an Graphics Object

graphics objecthoveringrectangle

I want the red rectangle to turn green while I'm hovering the mouse over it. How?
hax = axes('XLim', [0 4], 'YLim', [0 4]);
r = rectangle('Position', [1 1 1 1], 'FaceColor', 'r');

Best Answer

As a rough guide:
axesPos = getpixelposition( hax );
rectXPos = [1 2] / 4 * axesPos(3) + axesPos(1);
rectYPos = [1 2] / 4 * axesPos(4) + axesPos(2);
Then you will need to use the
WindowButtonMotionFcn
of the figure and create a function that tests the figure's
CurrentPoint
property against those rectXPos and rectYPos to see if you are inside the rectangle or not. The callback syntax will need to be something like
hFig.WindowButtonMotionFcn = @(src,evt) motionFunc( src, rectXPos, rectYPos );
and a function syntax e.g.
funcion motionFunc( hFig, rectXPos, rectYPos )
currentPoint = hFig.CurrentPoint;
% Do the obvious maths here of cyrrentPoint(1) against rectXPos and currentPoint(2) against rectYPos
I've probably missed out one or two things as I don't have time to give a full answer, but you should get the idea. Obviously the hard coded numbers in the recXPos and rectYPos maths should be replaced by calculations based on your rectangle position and axes limits rather than hard-coded.
If you allow zooming then these will need to be calculated dynamically because the XLim and YLim will change.