Explorar el Código

add: lcd新增lcd.getStrWidth函数以获取字符串的像素宽度

zengeshuai hace 5 meses
padre
commit
4a354fee60
Se han modificado 1 ficheros con 61 adiciones y 0 borrados
  1. 61 0
      components/lcd/luat_lib_lcd.c

+ 61 - 0
components/lcd/luat_lib_lcd.c

@@ -1156,6 +1156,67 @@ static int l_lcd_set_fontfile(lua_State *L) {
     return 1;
 }
 
+/*
+获取字符串宽度
+@api lcd.getStrWidth(str)
+@string str 要测量的字符串
+@return int 字符串的像素宽度
+@usage
+-- 设置字体
+lcd.setFont(lcd.font_opposansm12_chinese)
+-- 获取字符串宽度
+local width = lcd.getStrWidth("Hello世界")
+print("字符串宽度:", width)
+*/
+static int l_lcd_get_str_width(lua_State* L) {
+    size_t sz;
+    const uint8_t* data;
+    int total_width = 0;
+    
+    data = (const uint8_t*)luaL_checklstring(L, 1, &sz);
+    
+    if (sz == 0) {
+        lua_pushinteger(L, 0);
+        return 1;
+    }
+    
+    if (lcd_dft_conf == NULL) {
+        LLOGE("lcd not init");
+        lua_pushinteger(L, 0);
+        return 1;
+    }
+    
+    uint16_t e;
+    int16_t delta;
+    utf8_state = 0;
+    u8g2_t *u8g2 = &(lcd_dft_conf->luat_lcd_u8g2);
+
+    // 遍历字符串中的每个字符,累加宽度
+    for(;;){
+        e = utf8_next((uint8_t)*data);
+        if ( e == 0x0ffff )
+            break;
+        data++;
+        if ( e != 0x0fffe ){
+            // 只获取字符宽度,不绘制
+            const uint8_t *glyph_data = u8g2_font_get_glyph_data(u8g2, e);
+            if (glyph_data != NULL) {
+                u8g2_font_decode_t *decode = &(u8g2->font_decode);
+                u8g2_font_setup_decode(u8g2, glyph_data);
+                // 直接从解码后的数据获取 delta_x (字符宽度)
+                u8g2_font_decode_get_signed_bits(decode, u8g2->font_info.bits_per_char_x);
+                u8g2_font_decode_get_signed_bits(decode, u8g2->font_info.bits_per_char_y);
+                delta = u8g2_font_decode_get_signed_bits(decode, u8g2->font_info.bits_per_delta_x);
+                if (e < 0x0080) delta = luat_u8g2_need_ascii_cut(delta);
+                total_width += delta;
+            }
+        }
+    }
+    
+    lua_pushinteger(L, total_width);
+    return 1;
+}
+
 /*
 显示字符串
 @api lcd.drawStr(x,y,str,fg_color)