Skip to content
Edit this page

ictdesigntools.draw.text

Text sizes without a font engine: widths from Helvetica's published metrics (the face every output falls back to), close enough to fit labels to the space they have.

text_width

text_width(text: str, size: float) -> float

The width of text set at size (the em height), in the same units.

Source code in src/ictdesigntools/draw/text.py
def text_width(text: str, size: float) -> float:
    """The width of ``text`` set at ``size`` (the em height), in the same units."""
    total = 0
    for ch in text:
        i = ord(ch) - 32
        total += _WIDTHS[i] if 0 <= i < len(_WIDTHS) else _EXTRA.get(ch, _OTHER)
    return total * size / 1000

fit_size

fit_size(
    text: str,
    size: float,
    width: float,
    smallest: float = 0.0,
) -> float | None

The largest size up to size at which text fits in width, or None when it would have to be smaller than smallest.

Source code in src/ictdesigntools/draw/text.py
def fit_size(text: str, size: float, width: float, smallest: float = 0.0) -> float | None:
    """The largest size up to ``size`` at which ``text`` fits in ``width``, or None when it
    would have to be smaller than ``smallest``."""
    natural = text_width(text, size)
    if natural <= width:
        return size
    fitted = size * width / natural
    return fitted if fitted >= smallest and fitted > 0 else None

truncate

truncate(
    text: str,
    size: float,
    width: float,
    ellipsis: str = "…",
) -> str

text cut short with ellipsis to fit width at size; "" if nothing fits.

Source code in src/ictdesigntools/draw/text.py
def truncate(text: str, size: float, width: float, ellipsis: str = "…") -> str:
    """``text`` cut short with ``ellipsis`` to fit ``width`` at ``size``; "" if nothing fits."""
    if text_width(text, size) <= width:
        return text
    room = width - text_width(ellipsis, size)
    out = ""
    for ch in text:
        if text_width(out + ch, size) > room:
            break
        out += ch
    return out.rstrip() + ellipsis if out.strip() else ""

wrap

wrap(text: str, size: float, width: float) -> list[str]

text broken into lines at spaces to fit width; a word longer than the width is left on a line of its own.

Source code in src/ictdesigntools/draw/text.py
def wrap(text: str, size: float, width: float) -> list[str]:
    """``text`` broken into lines at spaces to fit ``width``; a word longer than the width is
    left on a line of its own."""
    lines: list[str] = []
    line = ""
    for word in text.split():
        trial = f"{line} {word}" if line else word
        if line and text_width(trial, size) > width:
            lines.append(line)
            line = word
        else:
            line = trial
    if line:
        lines.append(line)
    return lines