У меня есть некоторый код, который должен рисовать ограничивающие рамки вокруг каждого символа в предложении.
Я думаю, подушка возвращает неправильную высоту для некоторых знаков пунктуации, хотя отлично работает для букв и цифр. Как я могу получить точную высоту шрифта для «плохих» символов для шрифтов TrueType или, возможно, получить точные размеры ограничивающих рамок для них?
def draw_char_word_boxes(draw, x, y, text, color, font):
for i, char in enumerate(text):
right, _ = font.getsize(text[:i+1])
_, bottom = font.getsize(char)
width, height = font.getmask(char).size
right += x
bottom += y
top = bottom - height
left = right - width
draw.rectangle((left, top, right, bottom), None, color)
fnt = ImageFont.truetype('/usr/share/fonts/all/FreeMono.ttf', 30)
image = Image.new('RGB', (600, 500))
dr = ImageDraw.Draw(image)
# text = '"'
text = string.punctuation
color = (255,255,255)
dr.text((10,10), text, font=fnt, fill=color)
draw_char_word_boxes(dr, 10, 10, text, color, fnt)
dr.text((10,200), string.ascii_lowercase, font=fnt, fill=color)
draw_char_word_boxes(dr, 10, 200, string.ascii_lowercase, color, fnt)
![result](https://i.stack.imgur.com/3arEZ.png)