luat_lib_hzfont.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. @module hzfont
  3. @summary HzFont字体库
  4. @version 1.0
  5. @date 2025.10.16
  6. @tag LUAT_USE_HZFONT
  7. @usage
  8. -- 使用HzFont渲染TTF字体
  9. -- 需要准备TTF字体文件
  10. -- 初始化字体
  11. hzfont.init("/sd/font.ttf")
  12. */
  13. #include "luat_base.h"
  14. #include "luat_hzfont.h"
  15. #include "ttf_parser.h"
  16. #include "luat_lcd.h"
  17. #define LUAT_LOG_TAG "hzfont"
  18. #include "luat_log.h"
  19. #include "rotable2.h"
  20. #include "luat_conf_bsp.h"
  21. /**
  22. 初始化HzFont字体库
  23. @api hzfont.init([ttf_path][, cache_size][, load_to_psram])
  24. @string ttf_path TTF字体文件路径,可选;留空则回退到内置字库(若启用)
  25. @int cache_size 可选,位图与码点缓存容量(支持常量 HZFONT_CACHE_128/256/512/1024/2048),默认 HZFONT_CACHE_256
  26. @bool load_to_psram 可选,true 时将字库整包拷贝到 PSRAM 后再解析,减少后续 IO
  27. @return boolean 成功返回true,失败返回false
  28. @usage
  29. -- 从文件加载,使用默认缓存 256
  30. hzfont.init("/sd/font.ttf")
  31. -- 从文件加载,指定缓存 1024
  32. hzfont.init("/sd/font.ttf", hzfont.HZFONT_CACHE_1024)
  33. -- 从luadb文件系统加载
  34. hzfont.init("/luadb/font.ttf")
  35. -- 回退内置字库(启用 固件配置项 LUAT_CONF_USE_HZFONT_BUILTIN_TTF 时生效)
  36. hzfont.init()
  37. */
  38. static int l_hzfont_init(lua_State* L) {
  39. const char* ttf_path = NULL;
  40. size_t len = 0;
  41. if (!lua_isnoneornil(L, 1)) {
  42. ttf_path = luaL_checklstring(L, 1, &len);
  43. if (len == 0) {
  44. ttf_path = NULL;
  45. }
  46. }
  47. uint32_t cache_size = 0;
  48. if (!lua_isnoneornil(L, 2)) {
  49. cache_size = (uint32_t)luaL_checkinteger(L, 2);
  50. }
  51. int load_to_psram = 0;
  52. if (!lua_isnoneornil(L, 3)) {
  53. load_to_psram = lua_toboolean(L, 3);
  54. }
  55. int result = luat_hzfont_init(ttf_path, cache_size, load_to_psram);
  56. lua_pushboolean(L, result);
  57. return 1;
  58. }
  59. /* drawUtf8 已移至 lcd 模块的 lcd.drawHzfontUtf8 */
  60. /**
  61. 调试开关
  62. @api hzfont.debug(enable)
  63. @boolean enable true 开启,false 关闭
  64. @return boolean 总是返回true
  65. */
  66. static int l_hzfont_debug(lua_State* L) {
  67. int enable = lua_toboolean(L, 1);
  68. (void)ttf_set_debug(enable);
  69. lua_pushboolean(L, 1);
  70. return 1;
  71. }
  72. static const rotable_Reg_t reg_hzfont[] = {
  73. { "init", ROREG_FUNC(l_hzfont_init)},
  74. { "debug", ROREG_FUNC(l_hzfont_debug)},
  75. { "HZFONT_CACHE_128", ROREG_INT(128)},
  76. { "HZFONT_CACHE_256", ROREG_INT(256)},
  77. { "HZFONT_CACHE_512", ROREG_INT(512)},
  78. { "HZFONT_CACHE_1024", ROREG_INT(1024)},
  79. { "HZFONT_CACHE_2048", ROREG_INT(2048)},
  80. { NULL, ROREG_INT(0)}
  81. };
  82. LUAMOD_API int luaopen_hzfont(lua_State *L) {
  83. luat_newlib2(L, reg_hzfont);
  84. return 1;
  85. }