1. 程式人生 > 其它 >LVGL - grid 網格佈局

LVGL - grid 網格佈局

先從官方的這個簡單的例子來入手:

 1 /**
 2  * A simple grid
 3  */
 4 void lv_example_grid_1(void)
 5 {
 6     static lv_coord_t col_dsc[] = {70, 70, 70, LV_GRID_TEMPLATE_LAST};
 7     static lv_coord_t row_dsc[] = {50, 50, 50, LV_GRID_TEMPLATE_LAST};
 8 
 9     /*Create a container with grid*/
10     lv_obj_t * cont = lv_obj_create(lv_scr_act());
11 lv_obj_set_style_grid_column_dsc_array(cont, col_dsc, 0); 12 lv_obj_set_style_grid_row_dsc_array(cont, row_dsc, 0); 13 lv_obj_set_size(cont, 300, 220); 14 lv_obj_center(cont); 15 lv_obj_set_layout(cont, LV_LAYOUT_GRID); 16 17 lv_obj_t * label; 18 lv_obj_t * obj; 19 20 uint32_t i;
21 for(i = 0; i < 9; i++) { 22 uint8_t col = i % 3; 23 uint8_t row = i / 3; 24 25 obj = lv_btn_create(cont); 26 /*Stretch the cell horizontally and vertically too 27 *Set span to 1 to make the cell 1 column/row sized*/ 28 lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col, 1
, 29 LV_GRID_ALIGN_STRETCH, row, 1); 30 31 label = lv_label_create(obj); 32 lv_label_set_text_fmt(label, "c%d, r%d", col, row); 33 lv_obj_center(label); 34 } 35 }

其呈現出來效果如圖(使用PC模擬器,速度快)

通過修改引數的方法來快速瞭解函式功能如下:

static lv_coord_t col_dsc[] = {70, 70, 70, LV_GRID_TEMPLATE_LAST};

定義的是3列元素,每列的列寬=70;

static lv_coord_t row_dsc[] = {50, 50, 50, LV_GRID_TEMPLATE_LAST};

定義的是3行元素,每行的行高=50;

其中“LV_GRID_TEMPLATE_LAST”這個元素不能省略,否則程式會跑崩。官方說明書太潦草了,靠它根本就學不會。

然後就是建立一個網格容器,網格屬性就是上面定義好的行列屬性;

在之後就是在這個容器上建立3*3個btn物件。

lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col, 1,
29                                   LV_GRID_ALIGN_STRETCH, row, 1);

這個程式碼的作用就是把btn物件新增進單元格里。

這個例子是每個btn物件佔用一個單元格,我們修改下,讓每個物件佔用兩個單元格看看效果:

 1 void lv_example_grid_1(void)
 2 {
 3     static lv_coord_t col_dsc[] = {70, 70, 25, 25, 70, 70, LV_GRID_TEMPLATE_LAST};//擴充至6列
 4     static lv_coord_t row_dsc[] = {50, 50, 50, LV_GRID_TEMPLATE_LAST};
 5 
 6     /*Create a container with grid*/
 7     lv_obj_t * cont = lv_obj_create(lv_scr_act());
 8     lv_obj_set_style_grid_column_dsc_array(cont, col_dsc, 0);
 9     lv_obj_set_style_grid_row_dsc_array(cont, row_dsc, 0);
10     lv_obj_set_size(cont, 430, 220);//增大網格容器的X
11     lv_obj_center(cont);
12     lv_obj_set_layout(cont, LV_LAYOUT_GRID);
13 
14     lv_obj_t * label;
15     lv_obj_t * obj;
16 
17     uint32_t i;
18     for(i = 0; i < 9; i++) {
19         uint8_t col = i % 3;
20         uint8_t row = i / 3;
21 
22         obj = lv_btn_create(cont);
23         /*Stretch the cell horizontally and vertically too
24          *Set span to 1 to make the cell 1 column/row sized*/
25         lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col*2, 2,  //物件插入單元格的起始點是2的倍數
26                                   LV_GRID_ALIGN_STRETCH, row, 1);
27 
28         label = lv_label_create(obj);
29         lv_label_set_text_fmt(label, "c%d, r%d", col, row);
30         lv_obj_center(label);
31     }
32 }

看下效果,我們在改變每個btn佔用網格單元的同時,改變了第二個btn物件的大小。

本文來自部落格園,作者:月籠紗,轉載請註明原文連結:https://www.cnblogs.com/xjxcxjx/p/15767452.html,謝絕CSDN轉載!