使用 PIL 右对齐文本?

问题描述 投票:0回答:2

我有一个阿拉伯文本,想要将文本移动到图像的右上角。

我确实尝试在代码中使用

align='right'
也尝试过
direction=rtl
,但它在右上角显示图像的空白区域。

如果您想尝试该代码,请确保安装 libraqmraqm

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')

example of output image

python python-imaging-library
2个回答
0
投票

总结

  • 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()

结果

enter image description here


0
投票

当使用(0,0)时,起点从(左上角)开始。要填充右侧的空白区域,您需要考虑(右上角)部分 -> (max-X, 0)

接下来,使用锚点从右向左移动。

示例:

draw.text ( (3840,0),  wrapped, font=unicode_font, fill=font_color, spacing=30, anchor='rt')
© www.soinside.com 2019 - 2024. All rights reserved.