Skip to content

Rendered widths

Measure each unit's rendered text width headlessly — the width-step that drives the walk.

lexograph.layout.widths.rendered_widths(strings, *, prop=None, size=12.0)

Return the rendered width of each string, set in the given font.

Parameters:

Name Type Description Default
strings Iterable[str]

One string per unit (typically the sentences).

required
prop FontProperties | str | Path | None

The font to measure with — a :class:FontProperties, a path to a .ttf/.otf file, or None for matplotlib's default font.

None
size float

The font size to measure at (in points).

12.0

Returns:

Type Description
FloatArray

A float array of widths, one per input string. Empty or whitespace-only

FloatArray

strings get a width proportional to their character count so the walk

FloatArray

still advances past them.

Contract
  • The result has one entry per input string, all non-negative.
  • Widths are deterministic for a given font, size, and string.

Examples:

>>> w = rendered_widths(["i", "wwww"])
>>> bool(w[1] > w[0])
True
Source code in lexograph/layout/widths.py
def rendered_widths(
    strings: Iterable[str],
    *,
    prop: FontProperties | str | Path | None = None,
    size: float = 12.0,
) -> FloatArray:
    """Return the rendered width of each string, set in the given font.

    Args:
        strings: One string per unit (typically the sentences).
        prop: The font to measure with — a :class:`FontProperties`, a path to a
            ``.ttf``/``.otf`` file, or ``None`` for matplotlib's default font.
        size: The font size to measure at (in points).

    Returns:
        A float array of widths, one per input string. Empty or whitespace-only
        strings get a width proportional to their character count so the walk
        still advances past them.

    Contract:
        - The result has one entry per input string, all non-negative.
        - Widths are deterministic for a given font, size, and string.

    Examples:
        >>> w = rendered_widths(["i", "wwww"])
        >>> bool(w[1] > w[0])
        True
    """
    font = _as_font_properties(prop)
    widths: list[float] = []
    for string in strings:
        widths.append(_one_width(string, font, size))
    return np.asarray(widths, dtype=float)