我已经测试了计算,数学是正确的(并考虑了字体的高度和宽度),但在Python创建图像并将其放入Photoshop后,文本的垂直和水平居中对齐不正确。请问我应该用我的代码做些什么别的吗?
from PIL import Image, ImageDraw, ImageFont
# base = Image.open("Images/Phones/KK17018_Navy_KH10089.jpg").convert("RGBA")
base = Image.open('Images/Tablets/KK17076_Hunter_KH235.jpg').convert('RGB')
# Create blank rectangle to write on
draw = ImageDraw.Draw(base)
message = 'GGS'
num1, num2 = base.size
bounding_box = [0, 0, num1, num2]
x1, y1, x2, y2 = bounding_box # For easy reading
# font = ImageFont.truetype('Fonts/Circle/Circle Monograms Three White.ttf', size=413)
font = ImageFont.truetype('Fonts/Modern/Vhiena_Monoline.otf', size=800)
font2 = ImageFont.truetype('Fonts/Modern/Vhiena_Base.otf', size=800)
font3 = ImageFont.truetype('Fonts/Modern/Vhiena_Extrude A.otf', size=800)
# Calculate the width and height of the text to be drawn, given font size
w, h = draw.textsize(message, font=font3)
# Calculate the mid points and offset by the upper left corner of the bounding box
x = (x2 - x1 - w) / 2 + x1
y = (y2 - y1 - h) / 2 + y1
# Write the text to the image, where (x,y) is the top left corner of the text
draw.text((x, y), message, align='center', font=font3, fill='orange')
draw.text((x, y), message, align='center', font=font2, fill='black')
draw.text((x, y), message, align='center', font=font, fill='white')
# Draw the bounding box to show that this works
# draw.rectangle([x1, y1, x2, y2])
base.show()
base.save('test_image.jpg')
文本的左上角 x、y 坐标应为 (874,1399.5),但在 Photoshop 中显示为 (875,1586)。以上 Python 代码确实正确计算了 (874,1399.5),但某些内容使字体低于其应有的位置。
此外,我将字体堆叠在一起,因为它可以提供一个普通字体,一个阴影字体和一个让字体中间看起来是斜切的字体。是否有更好的方法,或者堆叠字体是可行的做法?
编辑:经过进一步测试,随着字体大小的增加,有些内容会给字体添加 22% 的顶部边距。我可以解决这个问题,但这似乎很奇怪。