How to align-center of a text in a lv_canvas' object?


I want to draw a text with center-align at a specific point in a lv_canvas’ object.
By the canvas’ api lv_canvas_draw_text(...) , I set last paramenter to
LV_LABEL_ALIGN_CENTER, but the result doesn’t look like correctly as align-center.

How to fix this issue?

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

  • ESP32
  • lvgl del7.0 ( maybe by lvgl 6.0.x, and lvgl dev 6.1 occur the same result ?)

What do you want to achieve?

Align center to a text at a point.

Code to reproduce

#define CANVAS_WIDTH  240
#define CANVAS_HEIGHT  240

void canvas_test() {
  lv_obj_t * canvas = lv_canvas_create(lv_scr_act(), NULL);
  lv_canvas_set_buffer(canvas, cbuf, CANVAS_WIDTH, CANVAS_HEIGHT, LV_IMG_CF_TRUE_COLOR);

  lv_canvas_fill_bg(canvas, LV_COLOR_RED, LV_OPA_COVER);

    static lv_style_t style; lv_style_copy(&style, &lv_style_plain);
    style.body.main_color = LV_COLOR_BLUE;
    style.body.grad_color = LV_COLOR_BLUE;
    style.body.radius     = LV_RADIUS_CIRCLE;
    style.text.color      = LV_COLOR_GREEN;

  lv_canvas_draw_rect( canvas, 5,10, 100,100, &style);
  lv_canvas_draw_text( canvas, 120,120, 240, &style, "HelloWorld", LV_LABEL_ALIGN_CENTER);

Screenshot and/or video


Your goal was to align the text horizontally to the middle, right?

It not working well in your example because max_w = 240 sets the text’s width to 240 and the text is centered in this width.

I’ve modified the text drawing like this:

  /*set x = 0, and max_w = 240*/
  lv_canvas_draw_text( canvas, 0,120, 240, &style, "HelloWorld", LV_LABEL_ALIGN_CENTER);


Oh, Thank you.

1 Like