如何使用Python绘制绕圆形弯曲的文本并实现文本到弧形图像的转换?
用Python实现弧形绕圆文本的图像生成
嘿,你的需求完全可以实现!虽然Pillow和OpenCV确实没有直接提供弧形文本的绘制API,但我们可以通过几何计算+逐字符绘制的方式来模拟这个效果。下面是我常用的解决方案,基于Pillow库,代码清晰易懂,还能灵活调整参数。
核心思路
绕圆弯曲的文本本质是让每个字符沿着圆弧的切线方向排列,每个字符的中心都落在指定的圆周上。我们需要:
- 确定圆心、圆弧半径,以及文本要占据的弧度范围
- 计算每个字符的宽度,分配对应的角度位置
- 逐个绘制字符,同时旋转字符使其与圆弧切线方向一致
完整代码示例
from PIL import Image, ImageDraw, ImageFont import math def draw_curved_text(text, output_path, font_path=None, font_size=40, radius=200, canvas_size=(500, 500), text_color=(0,0,0), bg_color=(255,255,255)): # 创建画布 img = Image.new('RGB', canvas_size, bg_color) draw = ImageDraw.Draw(img) # 加载字体(如果没指定路径,用默认字体) if font_path: font = ImageFont.truetype(font_path, font_size) else: font = ImageFont.load_default(size=font_size) # 计算每个字符的宽度,以及总文本宽度 char_widths = [draw.textlength(c, font=font) for c in text] total_text_width = sum(char_widths) # 计算文本占据的总弧度(弧度转角度:弧度*180/π) # 这里用总宽度除以半径得到弧度,确保文本刚好贴合圆弧 total_radians = total_text_width / radius # 起始角度(这里设置为让文本居中在上半圆,你可以调整) start_angle = math.pi - total_radians / 2 # 圆心坐标 center_x, center_y = canvas_size[0] // 2, canvas_size[1] // 2 current_angle = start_angle for i, char in enumerate(text): char_width = char_widths[i] # 计算当前字符中心对应的角度 char_radians = char_width / radius char_center_angle = current_angle + char_radians / 2 # 计算字符的位置(圆心偏移) x = center_x + radius * math.cos(char_center_angle) y = center_y + radius * math.sin(char_center_angle) # 计算字符的旋转角度:让字符垂直于圆弧切线,这里要转成角度 # 切线方向的角度是char_center_angle + π/2,转成degrees后还要调整方向 rotation_angle = math.degrees(char_center_angle + math.pi/2) # 创建单个字符的图像,旋转后粘贴到画布上 char_img = Image.new('RGBA', (font_size*2, font_size*2), (255,255,255,0)) char_draw = ImageDraw.Draw(char_img) char_draw.text((font_size, font_size), char, font=font, fill=text_color, anchor='mm') rotated_char = char_img.rotate(rotation_angle, expand=True) # 计算粘贴位置,让字符中心对齐(x,y) paste_x = int(x - rotated_char.width // 2) paste_y = int(y - rotated_char.height // 2) img.paste(rotated_char, (paste_x, paste_y), rotated_char) # 更新当前角度,处理下一个字符 current_angle += char_radians img.save(output_path) # 测试使用 if __name__ == '__main__': draw_curved_text( text="YOUR CURVED TEXT", output_path="curved_text.png", font_size=40, radius=180, canvas_size=(500, 500), text_color=(0, 0, 0), bg_color=(255, 255, 255) )
关键细节解释
- 弧度计算:用文本总宽度除以半径,得到文本需要占据的弧度,这样能保证文本自然贴合圆弧,不会太挤或太松
- 字符旋转:每个字符的旋转角度需要和圆弧切线方向一致,这样字符才会“顺着”圆弧弯曲
- 锚点对齐:绘制单个字符时用
anchor='mm'(中心对齐),粘贴时确保字符中心落在圆周上,避免偏移 - 参数调整:你可以修改
radius(圆弧半径)、start_angle(起始角度)来改变文本的位置和弯曲方向——比如把start_angle改成math.pi/2,文本会绕右半圆弧排列
注意事项
- 如果使用自定义字体,记得指定
font_path参数,确保字体文件路径正确 - 字符间距可以通过在文本中加空格,或者在代码里调整
char_radians的计算(比如额外加一点间距弧度) - 如果需要下半圆的弧形文本,只需要调整
start_angle为total_radians/2即可
这样运行代码后,你就能得到绕圆弯曲的文本图像啦!
内容的提问来源于stack exchange,提问作者np3228
相关产品推荐
相关产品推荐

