-
Notifications
You must be signed in to change notification settings - Fork 0
/
pil_autowrap.py
227 lines (161 loc) · 6.47 KB
/
pil_autowrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python
# pylint: disable=missing-module-docstring
import logging
import os
from typing import Optional, Tuple
from PIL import Image, ImageDraw, ImageFont # type: ignore
from PIL.ImageFont import FreeTypeFont # type: ignore
logging.basicConfig(level="DEBUG")
logger = logging.getLogger(__name__)
def wrap_text(
font: FreeTypeFont,
text: str,
max_width: int,
direction: str = "ltr",
) -> str:
"""
Wraps the text at the given width.
:param font: Font to use.
:param text: Text to fit.
:param max_width: Maximum width of the final text, in pixels.
:param max_height: Maximum height height of the final text, in pixels.
:param spacing: The number of pixels between lines.
:param direction: Direction of the text. It can be 'rtl' (right to
left), 'ltr' (left to right) or 'ttb' (top to bottom).
Requires libraqm.
:return: The wrapped text.
"""
words = text.split()
lines: list[str] = [""]
curr_line_width = 0
for word in words:
if curr_line_width == 0:
word_width = font.getlength(word, direction)
lines[-1] = word
curr_line_width = word_width
else:
new_line_width = font.getlength(f"{lines[-1]} {word}", direction)
if new_line_width > max_width:
# Word is too long to fit on the current line
word_width = font.getlength(word, direction)
# Put the word on the next line
lines.append(word)
curr_line_width = word_width
else:
# Put the word on the current line
lines[-1] = f"{lines[-1]} {word}"
curr_line_width = new_line_width
return "\n".join(lines)
# pylint: disable=too-many-arguments
def try_fit_text(
font: FreeTypeFont,
text: str,
max_width: int,
max_height: int,
spacing: int = 4,
direction: str = "ltr",
) -> Optional[str]:
"""
Attempts to wrap the text into a rectangle.
Tries to fit the text into a box using the given font at decreasing sizes,
based on ``scale_factor``. Makes ``max_iterations`` attempts.
:param font: Font to use.
:param text: Text to fit.
:param max_width: Maximum width of the final text, in pixels.
:param max_height: Maximum height height of the final text, in pixels.
:param spacing: The number of pixels between lines.
:param direction: Direction of the text. It can be 'rtl' (right to
left), 'ltr' (left to right) or 'ttb' (top to bottom).
Requires libraqm.
:return: If able to fit the text, the wrapped text. Otherwise, ``None``.
"""
words = text.split()
line_height = font.size
if line_height > max_height:
# The line height is already too big
return None
lines: list[str] = [""]
curr_line_width = 0
for word in words:
if curr_line_width == 0:
word_width = font.getlength(word, direction)
if word_width > max_width:
# Word is longer than max_width
return None
lines[-1] = word
curr_line_width = word_width
else:
new_line_width = font.getlength(f"{lines[-1]} {word}", direction)
if new_line_width > max_width:
# Word is too long to fit on the current line
word_width = font.getlength(word, direction)
new_num_lines = len(lines) + 1
new_text_height = (new_num_lines * line_height) + (
new_num_lines * spacing
)
if word_width > max_width or new_text_height > max_height:
# Word is longer than max_width, and
# adding a new line would make the text too tall
return None
# Put the word on the next line
lines.append(word)
curr_line_width = word_width
else:
# Put the word on the current line
lines[-1] = f"{lines[-1]} {word}"
curr_line_width = new_line_width
return "\n".join(lines)
# pylint: disable=too-many-arguments
def fit_text(
font: FreeTypeFont,
text: str,
max_width: int,
max_height: int,
spacing: int = 4,
scale_factor: float = 0.8,
max_iterations: int = 5,
direction: str = "ltr",
) -> Tuple[FreeTypeFont, str]:
"""
Automatically determines text wrapping and appropriate font size.
Tries to fit the text into a box using the given font at decreasing sizes,
based on ``scale_factor``. Makes ``max_iterations`` attempts.
If unable to find an appropriate font size within ``max_iterations``
attempts, wraps the text at the last attempted size.
:param font: Font to use.
:param text: Text to fit.
:param max_width: Maximum width of the final text, in pixels.
:param max_height: Maximum height height of the final text, in pixels.
:param spacing: The number of pixels between lines.
:param scale_factor:
:param max_iterations: Maximum number of attempts to try to fit the text.
:param direction: Direction of the text. It can be 'rtl' (right to
left), 'ltr' (left to right) or 'ttb' (top to bottom).
Requires libraqm.
:return: The font at the appropriate size and the wrapped text.
"""
initial_font_size = font.size
logger.debug('Trying to fit text "%s"', text)
for i in range(max_iterations):
trial_font_size = int(initial_font_size * pow(scale_factor, i))
trial_font = font.font_variant(size=trial_font_size)
logger.debug("Trying font size %i", trial_font_size)
wrapped_text = try_fit_text(
trial_font,
text,
max_width,
max_height,
spacing,
direction,
)
if wrapped_text:
logger.debug("Successfully fit text")
return (trial_font, wrapped_text)
# Give up and wrap the text at the last size
logger.debug("Gave up trying to fit text; just wrapping text")
wrapped_text = wrap_text(trial_font, text, max_width, direction)
return (trial_font, wrapped_text)
if __name__ == "__main__":
metadata_font = ImageFont.truetype("OpenSans-Regular.ttf", size=100)
text = "Welcome to Wikipedia, the free encyclopedia that anyone can edit. "
print(fit_text(metadata_font, text, 284, 120, max_iterations=10))