Python PIL:字体粗细和样式

时间:2018-01-15 07:19:29

标签: python fonts python-imaging-library pillow true-type-fonts

在我的电脑上,我只有一个用于Ubuntu Condensed字体的文件。即:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf 

但是,在LibreOffice中,我可以将此字体设为粗体和斜体: enter image description here

Ubuntu font tester网页上,我还可以为Ubuntu Condensed系列设置不同的字体粗细(即常规和粗体)和不同的字体样式(即正常和斜体)。在CSS中,这可能转化为:

/* CSS for bold and italic Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: italic;
font-weight: 700;

或者:

/* CSS for regular and normal Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: normal;
font-weight: 400;

然而,当涉及到Python的PIL / Pillow时,我在ImageFont中找不到任何可以修改字体样式和/或重量的工作选项,而不是使用ImageFont.truetype()加载不同的字体文件功能

对于“常规”Ubuntu字体(不是Condensed),我可以加载四个单独文件中的一个,以在Python中获得普通,粗体,斜体和粗体+斜体样式:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-RI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-BI.ttf

但不适用于Ubuntu Condensed。

所以问题是,是否可以在PIL / Pillow中使用粗体和/或斜体Ubuntu Condensed字体绘制图像?或者至少可以生成四个Ubuntu Condensed文件,以便它可以像Python中的Ubuntu字体一样使用?

1 个答案:

答案 0 :(得分:2)

您可以使用方法set_variation_by_name选择所需的字体变体。

要获取所有变体,请使用方法get_variation_names,该方法应为您提供名称列表。

>>> from PIL import ImageFont
>>> 
>>> font = ImageFont.truetype(...)
>>> font.get_variation_names()
[b'Normal', b'Bold', b'Italic', b'Bold, Italic']
>>> font.set_variation_by_name('Italic')

这应该为您提供所需的字体变体。