Search code examples
htmlmatlabiconsuicontrolmatlab-gui

How can I put an image on a Matlab uicontrol button?


I have Matlab 2019b, GUI Layout Toolbox 2.3.4 and t all runs on MacOs 14 Mojave.

I want to create button in in a UI that have icons/images instead of text. I have seen here:

https://undocumentedmatlab.com/blog/html-support-in-matlab-uicomponents/

that it is supposed to be possible to use HTML to render the button contents.

So - I try this sample code:

figure('MenuBar','none','Name','GUI-TEST','NumberTitle','off','Position',[200,200,140,90]);
push_btn = uicontrol('Style','PushButton','String','Push','Position',[30,60,80,20],...
  'CallBack','disp(''You are pressed a push button'')');
close_btn = uicontrol('Style','PushButton','String','Close','Position',[30,5,80,50],...
    'CallBack','close');
icon_file = fullfile(pwd, 'close.png')
str = ['<html><img src="file://' icon_file '"></html>']
set(close_btn,'String',str);

but it leaves me with an empty button.

enter image description here

If I deliberately use a filename that does not correspond to an existing file, I see a broken image icon:

enter image description here

So I am reasonably sure that the basic syntax and file path stuff is correct but the image does not get rendered in the button.

Is there something else I need to do to make this work or is it all just part of Matlab's overwhelming strangeness?


Solution

  • The easiest way to put an image on a uicontrol (and specifically a button), is to use the CData property,

    im_orig = imread(icon_file);  % Needs to be true color, i.e. MxNx3
    im_sized = imresize(im_orig,[80,50]); % size of the button
    % str = ['<html><img src="file://' icon_file '"></html>'];
    % set(close_btn,'String',str);
    set(close_btn,'CData',im_sized);