Search code examples
matlabtooltipmatlab-guide

How to display different infos when hovering over an image with mouse in matlab guide?


I have an image that consists of several segments with different labels. The labels are color coded. Does someone know how I can tell matlab to display the current label in a text box when hovering over it? I would basically need to display different text boxes depending on where on the image the mouse cursor is placed.

I found some examples using tooltip but these apply only to buttons and not to images depending on the exact pixel location that the mouse is hovering over.

Here is an example image: enter image description here


Solution

  • I'm not 100% clear on what you mean by "several labels", but I think you want to be able to display a popup edit over an image, I think the following does what you want:

    function hoverTest
      % create a figure (units normalized makes updating the position easier in the callback
      f = figure ( 'units', 'normalized' );
      % create an axes
      ax = axes ( 'parent', f );
      % load some data for plotting
      c = load ( 'clown' );
      % plot the data
      image ( c.X, 'parent', ax );
      % create a uipanel to host the text we will display
      uip = uipanel ( 'parent', f, 'position', [0 0 0.18 0.05], 'visible', 'off' );
      % create a text control to display the image info
      txt = uicontrol ( 'style', 'edit', 'parent', uip, 'units', 'normalized', 'position', [0 0 1 1] );
      % assign the callback for when the mouse moves
      f.WindowButtonMotionFcn =  @(obj,event)updateInfo(f,uip,ax,txt,c.X);
    end
    function updateInfo ( f, uip, ax, txt,img )
      % update the position of the uipanel - based on the current figure point (normalized units)
      set ( uip, 'Position', [f.CurrentPoint uip.Position(3:4)] );
      % Check to see if the figure is over the axes (if not hide)
      if ax.CurrentPoint(1,1) < min(ax.XLim) || ...
         ax.CurrentPoint(1,1) > max(ax.XLim) || ...
         ax.CurrentPoint(1,2) < min(ax.YLim) || ...
         ax.CurrentPoint(1,2) > max(ax.YLim)
       uip.Visible = 'off';
      else
        % show the panel
        uip.Visible = 'on';
        % get the current point
        cp = round(ax.CurrentPoint);
        % update the text string of the uicontrol
        txt.String = sprintf ( 'img(%i,%i) = %i', cp(1,1), cp(1,2), img(cp(1,2),cp(1,1) ) );
      end
    
    end