Tuesday, February 21, 2012

MATLAB GUI Inserting background image

Update [2014-04-13]: a function was created for inserting background image to MATLAB gui (or any figure for that matter). It can be found on github.

In many cases, you may wish to insert a background image to the existing GUI. Some of the uicontrols, such as pushbutton and toggle button, have the CData property, which you can set as background using data read from an image (see here). The gui itself, however, does not have such property, and a walk around is needed.

This tutorial shows how you can create an axes in the opening function of the gui and have the background image shown on the axes. To proceed, simply open up an existing gui (or create a new one), and insert the following code in the opening function of the gui.

% create an axes that spans the whole gui
ah = axes('unit', 'normalized', 'position', [0 0 1 1]); 
% import the background image and show it on the axes
bg = imread('example.jpg'); imagesc(bg);
% prevent plotting over the background and turn the axis off
set(ah,'handlevisibility','off','visible','off')
% making sure the background is behind all the other uicontrols
uistack(ah, 'bottom');

Note that the aspect ratio of the gui and the background image should match so that the appearance of the background image is optimized. 

Video walk-through 

18 comments:

  1. Thank you very much....

    ReplyDelete
  2. Thank you very much for this awesome trick

    ReplyDelete
  3. Thank you, awesome code :-)

    ReplyDelete
  4. This is really cool. Thank you very very much. :)

    ReplyDelete
  5. thank you men :D its amazing

    ReplyDelete
  6. Thanks ! Awesome work :)

    ReplyDelete
  7. Can I change this image? For example after button click?

    ReplyDelete
    Replies
    1. It should be possible.

      As long as you can retrieve the handle to the axes that stores the background image (say, in your button click call back), you can easily read in another image and then plot it on the axes.

      Delete
  8. is this is the same method used to import the image to GUI?

    ReplyDelete
    Replies
    1. Pretty much. Except you don't need to make the axes taking up the whole GUI and then send it to the back.

      Delete
  9. my axes doesnt show when i played the gui. it seems like my axes was behind the background image. i got all 7 axes. how to solve it gentleman?

    ReplyDelete
    Replies
    1. 7 axes? :-)

      I am guessing the "stack" was not set up properly. You want the axes that contains the background image to be at the bottom.

      If you can uistack(ah, 'bottom'); as the last line of your code, (where ah is where you background image is), you should be able to send the background image to the back so it doesn't block anything else.

      Delete