Estimate the number of characters that will fit into a rectangular text box. Parameters ---------- bbox : (x, y, height, width) # all in pixels font_size_px : int # font size in px avg_width_ratio : float # average char width ÷ fontSize line_height_ratio
(
bbox,
font_size_px=40 * (96 / 72), # Default font size in px (40pt converted to px)
*,
# Average glyph width as fraction of font-size (≈0.6 for monospace,
# ≈0.52–0.55 for most proportional sans-serif faces)
avg_width_ratio: float = 0.54,
line_height_ratio: float = 1,
# Optional inner padding in px that the renderer might reserve
padding_px: int = 0,
)
| 1017 | return int(round(new_width)), int(round(new_height)) |
| 1018 | |
| 1019 | def char_capacity( |
| 1020 | bbox, |
| 1021 | font_size_px=40 * (96 / 72), # Default font size in px (40pt converted to px) |
| 1022 | *, |
| 1023 | # Average glyph width as fraction of font-size (≈0.6 for monospace, |
| 1024 | # ≈0.52–0.55 for most proportional sans-serif faces) |
| 1025 | avg_width_ratio: float = 0.54, |
| 1026 | line_height_ratio: float = 1, |
| 1027 | # Optional inner padding in px that the renderer might reserve |
| 1028 | padding_px: int = 0, |
| 1029 | ) -> int: |
| 1030 | """ |
| 1031 | Estimate the number of characters that will fit into a rectangular text box. |
| 1032 | |
| 1033 | Parameters |
| 1034 | ---------- |
| 1035 | bbox : (x, y, height, width) # all in pixels |
| 1036 | font_size_px : int # font size in px |
| 1037 | avg_width_ratio : float # average char width ÷ fontSize |
| 1038 | line_height_ratio : float # line height ÷ fontSize |
| 1039 | padding_px : int # optional inner padding on each side |
| 1040 | |
| 1041 | Returns |
| 1042 | ------- |
| 1043 | int : estimated character capacity |
| 1044 | """ |
| 1045 | CHAR_CONST = 10 |
| 1046 | _, _, height_px, width_px = bbox |
| 1047 | |
| 1048 | usable_w = max(0, width_px - 2 * padding_px) |
| 1049 | usable_h = max(0, height_px - 2 * padding_px) |
| 1050 | |
| 1051 | if usable_w == 0 or usable_h == 0: |
| 1052 | return 0 # box is too small |
| 1053 | |
| 1054 | avg_char_w = font_size_px * avg_width_ratio |
| 1055 | line_height = font_size_px * line_height_ratio |
| 1056 | |
| 1057 | chars_per_line = max(1, math.floor(usable_w / avg_char_w)) |
| 1058 | lines = max(1, math.floor(usable_h / line_height)) |
| 1059 | |
| 1060 | return chars_per_line * lines * CHAR_CONST |
| 1061 | |
| 1062 | def estimate_characters(width_in_inches, height_in_inches, font_size_points, line_spacing_points=None): |
| 1063 | """ |