Skip to content

lcd.getTextSize

since 1.1.0

Get the dimensions that will be taken up with text when using the current parameters.

local width = lcd.getTextSize(text)

Parameters

Name Type Required Description
text string yes

Returns

width (integer): the width taken up

Examples

Returns width and height in pixels for the current font:

lcd.font(FONT_L)
local tw, th = lcd.getTextSize("12.6V")
lcd.drawText(w - tw - 4, h - th - 4, "12.6V")      -- bottom-right corner with 4 px margin

Find the biggest font that fits a box:

local FONTS = { FONT_XXL, FONT_XL, FONT_L, FONT_M, FONT_S }

local function fit(text, maxW, maxH)
  for i = 1, #FONTS do
    lcd.font(FONTS[i])
    local tw, th = lcd.getTextSize(text)
    if tw <= maxW and th <= maxH then return FONTS[i] end
  end
  return FONTS[#FONTS]
end

Tip

Measuring is not free. If the text only changes occasionally, cache the result and re-measure when the text, font or window size changes, as in the value widget recipe.

Used in

Real-world usage

Called 259 times across 10 open-source Ethos Lua projects. A few short excerpts:
local tw = lcd.getTextSize(text)

src/rfsuite/app/tile_grid.lua:95

local tw, th = lcd.getTextSize("")

src/bmfa-caller/widget_impl.lua:49

local tw, th = lcd.getTextSize(label)

src/wfsuite/widgets/dashboard.lua:517