簡體   English   中英

如何使用 PIL.ImageDraw.Draw.text 設置錨點以適合圖像中心的文本?

[英]How to set anchor to fit the text at center of image with PIL.ImageDraw.Draw.text?

使用 Pillow 庫在圖像上繪制文本,試圖通過選項anchor='mm'使文本適合錨定在圖像中心,但它看起來不完全是圖像中心。

演示代碼

from PIL import Image, ImageDraw, ImageFont

im = Image.new("RGBA", (500, 500), (255, 255, 255, 255))
font = ImageFont.truetype(font='arial.ttf', size=320)
draw = ImageDraw.Draw(im)
draw.text((250, 250), "123", font=font, fill='black', anchor='mm')
im.show()

結果:

在此處輸入圖像描述

期待:

在此處輸入圖像描述

文本看起來未對齊的原因是因為1的左側有一點邊距,pillow 將對齊包含此邊距的文本。

在兩端添加0將可視化它正確居中並且在1處有很大的邊距。

兩端為 0 的圖像

如果要對齊不包括邊距的文本, ImageFont.getmask很有幫助。

def get_offset_for_true_mm(text, draw, font):
    anchor_bbox = draw.textbbox((0, 0), text, font=font, anchor='lt')
    anchor_center = (anchor_bbox[0] + anchor_bbox[2]) // 2, (anchor_bbox[1] + anchor_bbox[3]) // 2
    mask_bbox = font.getmask(text).getbbox()
    mask_center = (mask_bbox[0] + mask_bbox[2]) // 2, (mask_bbox[1] + mask_bbox[3]) // 2
    return anchor_center[0] - mask_center[0], anchor_center[1] - mask_center[1]


im = Image.new("RGBA", (500, 500), (255, 255, 255, 255))
font = ImageFont.truetype(font='arial.ttf', size=320)
draw = ImageDraw.Draw(im)
text = "123"
offset = get_offset_for_true_mm(text, draw, font)
draw.text((250 + offset[0], 250 + offset[1]), text, font=font, fill='black', anchor='mm')
im.show()

結果:

圖像對齊,不包括邊距

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM