Loading Images from a different folder into App on Startup

I'm using the Matlab App Designer in Matlab 2020b, and I would like to have some buttons use an icon. I have the .png images for the icons in a folder within the directory of the .mlapp file. However, when I open an instance of Matlab and first load the app in Design View, the images are not found. I get the following error.
"Warning: File 'Down Arroow.png' is not on the MATLAB or specified path."
In the startupFcn of the app I added the following code.
addpath([pwd '\Assets\Sprites\'])
This is the path to the images from the run directory of the mlapp file.
When I run the app for the first time, the images also do not load.However, if I close the app and run again, the images do load. Furthermore, when I close the mlapp and re-open in the App Designer, the images will load in Design View.
Is there a way automatically load the images the first time I open the .mlapp file, without just putting all the images in the same directory as the malpp file? Alternatively, is there a way to make sure the images load when I press run for the first time? Would any of this cause problems if I decide to make the app an executable?

Answers (1)

You might want to set the parent directory as a variable in AppDesigner, and then use fullfile to generate the file names based on that.

That way you are not modifying the path after relying on it (which is the cause of the errors here). Not modifying the path is always best.

2 Comments

How would I create a parent directory variable before it used? The icons are used in the createComponents function, and it seems to me like the first place I can any code is the startupFcn, which is executed after createComponents. Is there a way to do it in the Designer GUI?
Since you're currently using pwd, you could use something like this:
app.pwd = pwd;
Then, when loading an image, you can use code like this:
im = imread(fullfile(app.pwd,'Assets','Sprites','Down Arroow.png'));
That way you can easily modify the parent directory in one place and you don't need to modify the path.
You will need to consider the case where your GUI will be loaded when it is not in the current directory.

Sign in to comment.

Categories

Products

Release

R2020b

Asked:

on 4 Aug 2023

Commented:

Rik
on 8 Aug 2023

Community Treasure Hunt

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

Start Hunting!