Python PIL 长文本换行
在使用PIL编写文字在图片上时,我们在知道api是只能编写一行,但是我们想要实现下图的描述文本的换行效果。
这个我们可以很简单的想到直接对文本做遍历计算长度切割就可以
# 设置字符串长度 def SetFixedStrLength(text): font = ImageFont.truetype('Arial Unicode.ttf', 20) # print(font.getsize(text)) strList = [] newStr = '' index = 0 for item in text: newStr += item if font.getsize(newStr)[0] > 380: # print(font.getsize(newStr)[0]) strList.append(newStr) newStr = '' # 如果后面长度不没有定长长就返回 if font.getsize(text[index:])[0] < 415: strList.append(text[index:]) break index += 1 resStr = '' count = 0 for item in strList: resStr += item+'\n' count += 1 return resStr, count
我们可以使用textwrap包来根据计算
from PIL import Image, ImageDraw, ImageFont import textwrap astr = '''The rain in Spain falls mainly on the plains.''' #这个设置文字个数 para = textwrap.wrap(astr, width=15) MAX_W, MAX_H = 200, 200 im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) font = ImageFont.truetype( '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 18) current_h, pad = 50, 10 for line in para: w, h = draw.textsize(line, font=font) draw.text(((MAX_W - w)/2, current_h), line, font=font) current_h += h + pad im.save('test.png')
参考文章:
https://blog.csdn.net/weixin_41768265/article/details/80338439
https://stackoverrun.com/cn/q/397428
原文地址:https://www.jianshu.com/p/67b821173f1d
相关推荐
-
解决Sklearn中使用数据集MNIST无法获取的问题(WinError 10060) python基础
2019-8-18
-
Python 游戏之旅(Pygame) python基础
2019-10-9
-
利用python开发app实战 python基础
2019-2-22
-
Python3 源码阅读 – 内存管理机制 python基础
2020-6-11
-
利用Python自动化自己的工作报表!不用担心因为报表被骂了! python基础
2019-8-27
-
浅谈UI自动化测试 python基础
2019-10-7
-
Python重启深信服设备 python基础
2019-10-9
-
Python:游戏:扫雷(附源码) python基础
2019-5-17
-
Neil 啃设计模式(0x04)建造者模式 python基础
2020-6-17
-
Python 代码优化实践 python基础
2019-8-25