我有一个阿拉伯文本,想要将文本移动到图像的右上角。
我确实尝试在代码中使用
align='right'
也尝试过direction=rtl
,但它在右上角显示图像的空白区域。
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import textwrap
#configuration
font_size=36
width=3840
height=390
back_ground_color=(255,255,255)
font_size=80
font_color=(0,0,0)
text = " وأيضا هذا النصح محبوب جدا جدا لذلك انا أفضلههذا النص مكتوب باللغةمكتوب باللغةمكتوب باللغةمكتوب باللغةمكتوب باللغة مكتوب باللغة العربية وهو واضح بشكل جميل"
wrapped = textwrap.fill(text, 100)
im = Image.new ( "RGB", (width,height), back_ground_color )
draw = ImageDraw.Draw ( im )
unicode_font = ImageFont.truetype("Sahel.ttf", font_size)
draw.text ( (0,0), wrapped, font=unicode_font, fill=font_color,spacing=30,direction='rtl',align='right',features='rtla')
im.save('text.png')
align
参数可用于较小的行(通常是最后一行),以便根据文本框对齐它们draw.textsize
函数来获取文本框大小并根据图像大小计算其位置。from PIL import Image, ImageDraw, ImageFont
import textwrap
# configuration
font_size = 36
width = 3840
height = 390
back_ground_color = (255, 255, 255)
font_size = 80
font_color = (0, 0, 0)
text = " وأيضا هذا النصح محبوب جدا جدا لذلك انا أفضلههذا النص مكتوب باللغةمكتوب باللغةمكتوب باللغةمكتوب باللغةمكتوب باللغة مكتوب باللغة العربية وهو واضح بشكل جميل"
wrapped = textwrap.fill(text, 100)
im = Image.new("RGB", (width, height), back_ground_color)
draw = ImageDraw.Draw(im)
unicode_font = ImageFont.truetype("Sahel Regular.ttf", font_size)
# get text box size
text_w, text_h = draw.textsize(wrapped, font=unicode_font, direction="rtl", language="ar")
draw.text(
# (0, 0), # top left corner
# (width - text_w, 0), # top right corner
# (width - text_w, height - text_h), # bottom right corner
# (0, height - text_h), # bottom left corner
# ((width - text_w) // 2, (height - text_h) // 2), # center
(width - text_w, (height - text_h) // 2), # center vertical + start from right
wrapped,
font=unicode_font,
fill=font_color,
direction='rtl',
language='ar',
align='left', # affect the second line of the text, set to right to see the last line aligned to the right
)
im.show()
当使用(0,0)时,起点从(左上角)开始。要填充右侧的空白区域,您需要考虑(右上角)部分 -> (max-X, 0)
接下来,使用锚点从右向左移动。
示例:
draw.text ( (3840,0), wrapped, font=unicode_font, fill=font_color, spacing=30, anchor='rt')