说话泡泡生成图片程序

"""说话泡泡生成程序,这是为了给turtle.py模块增加"说话"功能的一个测试程序。就是在角色的头顶右上方或左上方的那个说话泡泡。这是实时生成的一个图片。"""


from PIL import ImageFont,Image,ImageDraw,ImageOps 


def make_string2image(string,width_every_line,font,fontcolor,bgcolor):
    """把字符串分成一行一行相等的,然后转换图形对象"""   
    if len(string) < 8 :
        unuber = 1+(8 - len(string)) // 2  # 左右两边要补偿的空格数
        string = " " * unuber   + string + " "* unuber
    width = 0 
    strings = []
    s = ""
    for c in string:                     # 把string整理成相同像素宽度的行        
        if width <= width_every_line and c != '\n':
            s = s + c                    
            width += font.getsize(c)[0]        
        else:        
            strings.append(s)
            if c!='\n':
                s = c
            else:
                s = ""
            width = 0       
    strings.append(s)

    row_spacing = font.getsize(strings[0])[1] // 2 # 第一行的高度的一半做为行距
    total_width = width_every_line 
    total_height = row_spacing                     # 起始值
    points=[]                                      # Draw的每行起始坐标点
    minwidth = width_every_line
    maxwidth = width_every_line
    for s in strings:
        w = font.getsize(s)[0] 
        if w > maxwidth : maxwidth = w      # 最大宽宽字符串
        if w < minwidth : minwidth = w      # 最小宽度字符串长度
        h = font.getsize(s)[1]
        points.append((row_spacing*2,total_height))
        total_height += (h + row_spacing//2)         
    total_height +=   row_spacing
     
    if len(strings) == 1 :    
        total_width = row_spacing + minwidth + row_spacing * 3
        
    else:
        total_width = row_spacing + maxwidth + row_spacing * 3     
     
    im = Image.new("RGB", (total_width, total_height), bgcolor)
    
    draw = ImageDraw.Draw(im)

    index = 0
    for s in strings:
        x = points[index][0]
        y = points[index][1]
        draw.text((x, y), s, fontcolor, font=font)
        index = index + 1
    return im

You must log in to read the rest of this article. Please log in or register as a user.