Python中使用drawString()绘制带有背景颜色的文本
发布时间:2024-01-14 03:31:25
在Python中,可以使用PIL库(Python Imaging Library)来绘制带有背景颜色的文本。下面是使用PIL库的例子:
from PIL import Image, ImageDraw, ImageFont
# 创建一个带有背景颜色的图片
background_color = (255, 255, 255) # 背景颜色为白色
image_width = 300 # 图片宽度
image_height = 100 # 图片高度
image = Image.new('RGB', (image_width, image_height), background_color)
# 创建绘制对象
draw = ImageDraw.Draw(image)
# 设置字体样式和大小
font_path = 'arial.ttf' # 字体文件路径
font_size = 24 # 字体大小
font = ImageFont.truetype(font_path, font_size)
# 设置文本内容和颜色
text_content = 'Hello, World!'
text_color = (0, 0, 0) # 文本颜色为黑色
# 获取文本的宽度和高度
text_width, text_height = draw.textsize(text_content, font)
# 计算文本在图片上的位置
x = (image_width - text_width) // 2 # 水平居中
y = (image_height - text_height) // 2 # 垂直居中
# 绘制背景矩形
text_background_color = (255, 0, 0) # 文本背景颜色为红色
text_background_width = text_width + 10 # 背景矩形宽度比文本宽度多10个像素
text_background_height = text_height + 10 # 背景矩形高度比文本高度多10个像素
text_background_x = x - 5 # 背景矩形的x坐标比文本位置的x坐标小5个像素
text_background_y = y - 5 # 背景矩形的y坐标比文本位置的y坐标小5个像素
text_background = (text_background_x, text_background_y, text_background_x + text_background_width, text_background_y + text_background_height)
draw.rectangle(text_background, fill=text_background_color)
# 绘制文本
draw.text((x, y), text_content, font=font, fill=text_color)
# 保存图片
image.save('text_with_background.png')
上述代码首先创建了一个宽度为300,高度为100的白色背景图像,然后使用ImageDraw对象进行绘制操作。设置字体样式和大小后,通过draw.textsize()函数获取文本的宽度和高度。
接下来,计算文本在图片上的位置,使其居中显示。然后设置文本背景矩形的位置和颜色,并使用draw.rectangle()函数绘制背景矩形。
最后,使用draw.text()函数绘制文本。绘制完成后,使用image.save()函数将图像保存到文件中。
执行上述代码后,会生成一个带有红色背景和黑色文本的图片文件text_with_background.png。
需要注意的是,在执行上述代码前,需要先安装PIL库。可以使用以下命令进行安装:
pip install pillow
另外,需要将字体文件arial.ttf放在与代码文件相同的目录下,或根据具体的字体文件路径进行设置。
