python - 如何在 Python Pillow 中设置字体的字距调整?

标签 python python-imaging-library

对于 Pillow 类 ImageDraw ( https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.ImageDraw.text ),我找到了参数 features。它可以调整这个字体参数:https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist

如何设置字距调整(kern)参数?我不懂语法。

这是行不通的:

draw.text((61, 386), text, (0, 0, 0), font=font, features={"kern": 1.0})

最佳答案

我最近遇到了同样的问题。我决定最好的方法是单独绘制每个字母并计算使其均匀所需的间距。这是我使用的代码。

text = "Sample Text"
total_text_width, total_text_height = draw.textsize(text, font=font)
width_difference = desired_width_of_text - total_text_width
gap_width = int(width_difference / (len(text) - 1))
xpos = left_side_padding
for letter in text:
    draw.text((xpos,0),letter, (0,0,0), font=font)
    letter_width, letter_height = draw.textsize(letter, font=font)
    xpos += letter_width + gap_width
  • desired_width_of_text 需要设置,指定想要的文字宽度
  • left_side_padding 应为 0 或从左侧指定任何填充
  • font 需要指定合适大小的字体

default spacing vs drawing each letter and calculating spacing

关于python - 如何在 Python Pillow 中设置字体的字距调整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58591305/

相关文章:

python - 我正在尝试检测屏幕上的移动但收到错误 : ValueError: too many values to unpack (expected 4)

PIL中的python图像大小函数

python - 尝试比较 Python pandas dataframe 中的日期时出现错误

python - 子进程.Popen : 'OSError: [Errno 2] No such file or directory' only on Linux

python - 用另一个 df 中的行替换 Pandas df 中的行

python - 用线条粗细在Python PIL中绘制椭圆

使用线程的 Pythonic 方式

python - 对于Where条件中的语法

python - 如何将 24 帧编码为一张 24 位 RGB 图像?

python - 用宽线修复 PIL.ImageDraw.Draw.line