Label background color

Description

I’m trying to change the color of a label but fail to do so.

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

ESP32 with Arduino IDE

What LVGL version are you using?

Latest

What do you want to achieve?

I want to create a label that eventually needs to display the time/date.
I want to change the background color of the label to black, but fail to do so.

What have you tried so far?

Defined a style and applied it to the label. However the background color of the label is white(or silver?) and not black. When I change the text color to black for example I can see the correct text color on the screen. (Everythin compiles ok by the way)

Code to reproduce

lv_style_init(&topstyle);
lv_style_set_bg_color(&topstyle, LV_STATE_DEFAULT, LV_COLOR_BLACK);
lv_style_set_text_color(&topstyle, LV_STATE_DEFAULT, LV_COLOR_WHITE);
//Set date

  lv_obj_t *label = lv_label_create(lv_scr_act(), NULL);
  lv_label_set_text(label, "This is a test");
  lv_obj_align(label, NULL, LV_ALIGN_IN_TOP_LEFT, topkoor[2][0], topkoor[2][1]);
   lv_obj_set_width(label,135);
   lv_obj_set_height(label,22);
  lv_obj_add_style(label, LV_LABEL_PART_MAIN, &topstyle);

Screenshot and/or video

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

Hi @MisterA,

I am fairly sure the label object is not intended to work in this manner. It’s my understanding a label is always transparent by design. (I am sure someone will correct me if I am wrong!)

You could maybe do it this way:

	lv_obj_t *bkgrnd = lv_obj_create(lv_scr_act(), NULL);
	lv_obj_set_width(bkgrnd,135);
	lv_obj_set_height(bkgrnd,22);
	lv_obj_t *label = lv_label_create(bkgrnd, NULL);
	lv_label_set_text(label, "This is a test");
	lv_obj_set_style_local_text_color( label, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE );
	lv_obj_set_style_local_bg_color( bkgrnd, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK );

	lv_obj_align(bkgrnd, NULL, LV_ALIGN_IN_TOP_LEFT, 10, 10);
	lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);

Another option is to use a single line lv_text_area and set the background colour of that object.

I hope this helps…

Kind Regards,

Pete

I think if you change bg_opa on the label it will draw its background. If I recall correctly, this is the modern replacement for the old body_draw flag.

2 Likes

Thank you for your reply. I tried your suggestion and now I’m getting the results you can see in the pictures. When I press on that area it gets focus I guess and the border turns red. 1594813371054

I will have a look at the bg_opa suggestion as well.

Hi @MisterA ,

Hopefully @embeddedt 's suggestion is a good solution, but if you draw a blank, you should be able to address the focus issue by calling: void lv_obj_set_click(lv_obj_t *obj, bool en) on the background object and setting it to false. You can also remove or set the border to black using the styles if you wish.

Kind Regards,

Pete