Define image buttons from string arrays


For my application I would need to display 4 buttons per screen or page.
I would like to declare/define the image buttons using for loops.

I apologize if this is more of a C programming question.

What MCU/Processor/Board and compiler are you using?

ESP32 with Arduino IDE

What do you want to achieve?

I want to declare a list of images, declare them in a for loop.
Then define the buttons in another for loop.

What have you tried so far?

Code to reproduce

This is a bit of “pseudo” code…

//4 button + 4 button checked images
char *bimages[]={"b1","b1chkd","b2","b2chkd","b3","b3chkd","b4","b4chkd"};
//button coordinates
int btnkoor[4][2] = {{0,23},{120,23},{0,143},{120,143}};
//array of 4 image buttons
lv_obj_t * imgbuttons[4];
//button pressed style - darken when pressed
static lv_style_t style; 
lv_style_set_image_recolor_opa(&style, LV_STATE_PRESSED, LV_OPA_30);    
lv_style_set_image_recolor(&style, LV_STATE_PRESSED, LV_COLOR_BLACK);    
lv_style_set_text_color(&style, LV_STATE_DEFAULT, LV_COLOR_WHITE);

int x;
//declare images
for(x=0;x<4;x++){ LV_IMG_DECLARE(myimages[x]);} //doesn't work, don't know how to do this properly
//define buttons
 lv_imgbtn_set_src(imgbuttons[x], LV_BTN_STATE_RELEASED, &bimages[(x*2)]);
    lv_imgbtn_set_src(imgbuttons[x], LV_BTN_STATE_PRESSED, &bimages[(x*2)]);
    lv_imgbtn_set_src(imgbuttons[x], LV_BTN_STATE_CHECKED_RELEASED, &bimages[(x*2)+1]);
    lv_imgbtn_set_src(imgbuttons[x], LV_BTN_STATE_CHECKED_PRESSED, &bimages[(x*2)+1]);
    lv_imgbtn_set_checkable(imgbuttons[x], true);
    lv_obj_add_style(imgbuttons[x], LV_IMGBTN_PART_MAIN, &style);
    lv_obj_align(imgbuttons[x], NULL, LV_ALIGN_IN_TOP_LEFT, btnkoor[x][0], btnkoor[x][1]);

Screenshot and/or video

If possible, add screenshots and/or videos about the current state.

You can’t declare images in for loops, because C is not a very dynamic language. You can either:

  • write out all of the lv_imgbtn_set_src calls by hand, or
  • declare all the images statically and then make a set of constant pointer arrays, like so:
/* global scope */

static const lv_img_dsc_t *regular_images[] = {
static const lv_img_dsc_t *checked_images[] = {

Then you can loop with x from 0 to 4 and pass regular_images[i] (not &regular_images[i]!) to the lv_imgbtn_set_src function.