如何使用 PIL 右对齐文本?

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

我有一些阿拉伯文本,想将其渲染在图像的右上角。

我尝试使用

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

(请注意,需要 libraqmraqm 插件。)

产生以下结果: example of output image

怎样才能让文字出现在正确的位置?

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

默认情况下,

(0, 0)
点表示将在其中绘制文本的边界框的左上角。为了避免出现空白,您需要将此框的右上角与
max-X, 0
对齐。

您可以使用

anchor
参数来表示文本坐标应位于文本的右上角,以便从右向左流动,如下所示:

draw.text ( (3840,0),  wrapped, font=unicode_font, fill=font_color, spacing=30, anchor='rt')

1
投票

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

这会产生:

corrected example image with properly right-aligned text

© www.soinside.com 2019 - 2024. All rights reserved.