[英]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.