简体   繁体   English

PIL:我可以有多种大小的相同字体的文本吗? (Python)

[英]PIL: can i have multiple sizes of text of the SAME font? (Python)

Currently trying to have the same font for an image with PIL but with different sizes.目前正在尝试为带有 PIL 但大小不同的图像使用相同的字体。

Tried to have two different font instances but it didn't work.试图有两种不同的字体实例,但没有用。 How can I do that?我怎样才能做到这一点?

If you're using ImageFont.truetype() , you'll need multiple instances for multiple sizes.如果您使用ImageFont.truetype() ,您将需要多个大小的多个实例。

You could neatly wrap this using functools.lru_cache() so a single font/size gets loaded only once during your app:您可以使用functools.lru_cache()巧妙地包装它,以便在您的应用程序期间只加载一次单个字体/大小:

from functools import lru_cache

get_font = lru_cache()(ImageFont.truetype)

draw.text((10, 10), "hello", font=get_font("Arial.ttf", 10))
draw.text((10, 50), "world", font=get_font("Arial.ttf", 50))

I think you mean this:我想你的意思是:

#!/usr/bin/env python3

from PIL  import Image, ImageFont, ImageDraw

# Create a black canvas
canvas = Image.new('RGB', (400,200))

# Get a drawing context
draw = ImageDraw.Draw(canvas)
monospace20 = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",20)
monospace50 = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",50)

draw.text((10, 10), "Hello 20", font=monospace20, fill=(255,255,255))
draw.text((10, 90), "Hello 50", font=monospace50, fill=(255,255,255))

canvas.save('result.png')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Tkinter在同一文本上有2种不同的字体大小 - Tkinter have 2 different font sizes on the same text matplotlib轴标签中可以有两种不同的字体大小吗? - Can I have two different font sizes in a matplotlib axes label? 同一个 Matplotlib 标签中的多种字体大小 - Multiple font sizes in same Matplotlib label 如何将具有多个文本列表值的python字典拆分为具有相同值的键的单独字典? - How can I split a python dictionary with multiple text-list values to have separate dictionaries of keys that have the same values? 使用python和PIL如何获取图像中的文本块? - Using python and PIL how can I grab a block of text in an image? PIL TypeError:text()有多个参数'font'的值 - PIL TypeError: text() has multiple values for argument 'font' 是否可以在同一个字符串上使用两种字体大小(对于 label 或按钮)? - is it possible to have two font sizes on the same string (for a label or button)? PyQt5 - 我可以在 label 中文本的不同部分使用不同的字体大小吗? - PyQt5 - Can I use different font sizes on different parts of the text in a label? 为什么来自PIL的ImageFont无法在Python中加载印尼字体? - Why ImageFont from PIL can't load Indonesia font in Python? 如何使用 Python 在一行中配置不同字体大小的 tesseract? - How can I configure tesseract for different font sizes in one line with Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM