每行開始遇到標點符號會自動加入前一行
# coding=utf-8
import re
from PIL import Image, ImageDraw, ImageFont
LINE_CHAR_COUNT = 12*2 # 每行字符數:12個中文字符
TABLE_WIDTH = 4
def line_break(line):
ret = ''
width = 0
for c in line:
if len(c.encode('utf8')) == 3: # 中文
if LINE_CHAR_COUNT == width + 1: # 剩余位置不夠一個漢字
width = 2
ret += '\n' + c
else: # 中文寬度加2,注意換行邊界
width += 2
ret += c
else:
if c == '\t':
space_c = TABLE_WIDTH - width % TABLE_WIDTH # 已有長度對TABLE_WIDTH取余
ret += ' ' * space_c
width += space_c
elif c == '\n':
width = 0
ret += c
else:
width += 1
ret += c
if width >= LINE_CHAR_COUNT:
ret += '\n'
width = 0
if ret.endswith('\n'):
return ret
return ret + '\n'
output_str = "白內障人群發病年齡多見於、40歲以上,其中60-8,9歲人群中,白內障發病率高、達80%" # 測試字符串
output_str = line_break(output_str)
split_lines = output_str.split('\n') # 計算行數
split_lines = [var for var in split_lines if var] # 去除空數組
arr = [',', '、', '。', ',','!',"?","?","!","-"]
print(split_lines)
for item in range(0,len(split_lines)):
symbol = split_lines[item][0] # 獲取符號
print(symbol)
if (symbol in arr):
if len(split_lines) > item+1:
split_lines[item] = split_lines[item] + split_lines[item + 1][0]
split_lines[item + 1] = split_lines[item + 1][1:]
split_lines[item] = split_lines[item][1:]
split_lines[item - 1] = split_lines[item - 1] + symbol
print(split_lines)
split_lines = "\n".join(split_lines)
d_font = ImageFont.truetype('SIMLI.TTF', 60)
image = Image.open("/Users/xywy/Desktop/WechatIMG5039.jpeg")
draw_table = ImageDraw.Draw(im=image)
draw_table.text(xy=(160, 150), text=split_lines, fill=(255,255,255), font= d_font, spacing=4) # 文字位置,內容,字體
image.show() # 直接顯示圖片
# image.save('comments.png', 'PNG') # 保存在當前路徑下,格式為PNG
image.close()