【问题标题】:How to make pillow text not get offscreen如何使枕头文字不会离开屏幕
【发布时间】:2021-10-07 02:33:00
【问题描述】:

我做了一个向图像添加文本的命令。但问题是,有时如果有人输入长消息,文本就会离开屏幕。我该如何解决这个问题?

@bot.command()
async def Picture1(ctx,*,message=None):

    member = ctx.author
    if message ==None:
        await ctx.send("You have to put a message in idiot")
        return

    text1 = str(member)
    print(text1)

    # get an image
    base = Image.open(r"C:\Users\User\Pictures\Picture.png").convert("RGBA")

    # make a blank image for the text, initialized to transparent text color
    txt = Image.new("RGBA", base.size, (255, 255, 255, 0))

    # get a font
    fnt = ImageFont.truetype(
        r"C:\Users\User\fonts\courbi.ttf", 40)
    # get a drawing context
    d = ImageDraw.Draw(txt)

    # draw text, half opacity
    d.text((21, 70), "'" + message + "'", font=fnt,
           fill=(255, 255, 255, 128))
    # draw text, full opacity
    d.text((10, 213), "-" + text1, font=fnt, fill=(255, 255, 255, 255))

    out = Image.alpha_composite(base, txt)

    out.save("picutre1.png", format="png")
    print(out.save)

    await ctx.send(file=discord.File("quote.png"))

【问题讨论】:

    标签: python discord.py python-imaging-library


    【解决方案1】:

    使用this 回答以像素为单位计算文本的大小,然后您可以选择缩小文本或只换行。

    来自该答案的内容:

    import ctypes
    
    def GetTextDimensions(text, points, font):
        class SIZE(ctypes.Structure):
            _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]
    
        hdc = ctypes.windll.user32.GetDC(0)
        hfont = ctypes.windll.gdi32.CreateFontA(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
        hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
        size = SIZE(0, 0)
        ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text.encode('cp1252'), len(text), ctypes.byref(size))
        ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
        ctypes.windll.gdi32.DeleteObject(hfont)
        return (size.cx, size.cy)
    

    如果您只想使文本适合,我已经制作了一个函数来获得适合的大小:

    def resizetofit(text,sz,fontname,max_horizontal):
        while True:
            width, height = GetTextDimensions(text, sz, fontname) #Get size of text
            if width < max_horizontal:
                break
            else:
                sz -= 1
        return sz
    

    用法:textsize = resizetofit("text", default text size, "fontName", horizontal max size in pixels)

    或者,如果您想在不合适的情况下换行,请告诉我,我可以尝试创建一个函数来执行此操作,但我链接的答案包含您自己制作所需的一切。

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      相关资源
      最近更新 更多