Skip to content
measure_text

measure_text

Mojo function 🡭

measure_text

fn def measure_text(text: String, size: Float64, family: String = "Sans", slant: FontSlant = FontSlant.NORMAL, weight: FontWeight = FontWeight.NORMAL, kerning: Bool = True, ligatures: Bool = True) -> TextMetrics

Measure text at size points in family without drawing it.

Treats text as a single line: embedded “\n” gets no line-break handling. Split on “\n” and call this per line for a multi-line string.

Builds a FontCache per call, which rescans every font file installed on the machine – tens of milliseconds, against tens of microseconds once a cache exists. Fine for a one-off string; for more than a couple, construct one FontCache and use the cache= overload below.

Args:

  • text (String): Text to measure, treated as a single line.
  • size (Float64): Font size in points.
  • family (String): Font family name or generic alias.
  • slant (FontSlant): Requested upright/italic/oblique style.
  • weight (FontWeight): Requested normal/bold weight.
  • kerning (Bool): Apply the font’s pair kerning between adjacent glyphs.
  • ligatures (Bool): Apply the font’s GSUB shaping – ligatures and Arabic contextual forms. False lays out one glyph per character.

Returns:

TextMetrics: text’s width/height/advance at that size.

Raises:

fn def measure_text(text: String, size: Float64, family: String = "Sans", slant: FontSlant = FontSlant.NORMAL, weight: FontWeight = FontWeight.NORMAL, kerning: Bool = True, ligatures: Bool = True, *, mut cache: FontCache) -> TextMetrics

Like measure_text above, but resolving fonts through cache. Pass the same FontCache to every call in a batch.

Args:

  • text (String): Text to measure, treated as a single line.
  • size (Float64): Font size in points.
  • family (String): Font family name or generic alias.
  • slant (FontSlant): Requested upright/italic/oblique style.
  • weight (FontWeight): Requested normal/bold weight.
  • kerning (Bool): Apply the font’s pair kerning between adjacent glyphs.
  • ligatures (Bool): Apply the font’s GSUB shaping – ligatures and Arabic contextual forms. False lays out one glyph per character.
  • cache (FontCache): Shared cache for font resolution and parsed faces.

Returns:

TextMetrics: text’s width/height/advance at that size.

Raises: