先从官方的这个简单的例子来入手:
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对象的大小。