如何使用PIL的ImageFont类获取字体像素高度? [英] How to get the font pixel height using PIL's ImageFont class?

查看:147
本文介绍了如何使用PIL的ImageFont类获取字体像素高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PIL的ImageFont模块加载字体以生成文本图像.我希望文本紧紧地绑在边缘上,但是,当使用ImageFont获取字体高度时,似乎它包含了字符的填充.如红色矩形所示.

I am using PIL' ImageFont module to load fonts to generate text images. I want the text to tightly bound to the edge, however, when using the ImageFont to get the font height, It seems that it includes the character's padding. As the red rectangle indicates.

c = 'A'
font = ImageFont.truetype(font_path, font_size)
width = font.getsize(c)[0]
height = font.getsize(c)[1]
im = Image.new("RGBA", (width, height), (0, 0, 0))
draw = ImageDraw.Draw(im)
draw.text((0, 0), 'A', (255, 255, 255), font=font)
im.show('charimg')

如果我可以得到字符的实际高度,那么我可以跳过底部矩形中的边界行,可以从字体中获得此信息吗?谢谢.

If I can get the actual height of the character, then I could skip the bounding rows in the bottom rectangle, could this info got from the font? Thank you.

推荐答案

确切大小取决于许多因素.我将向您展示如何计算字体的不同指标.

Exact size depends on many factors. I'll just show you how to calculate different metrics of font.

font = ImageFont.truetype('arial.ttf', font_size)
ascent, descent = font.getmetrics()
(width, baseline), (offset_x, offset_y) = font.font.getsize(text)

  • 红色区域的高度: offset_y
  • 绿色区域的高度:上升-offset_y
  • 蓝色区域的高度:下降
  • 黑色矩形: font.getmask(text).getbbox()
  • 希望有帮助.

    这篇关于如何使用PIL的ImageFont类获取字体像素高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆