簡體   English   中英

使用 PIL 繪制粗體/斜體文本?

[英]Draw bold/italic text with PIL?

如何使用 PIL 繪制粗體/斜體文本? ImageFont.truetype(file, size) 有一個僅指定字體大小的選項。

使用粗體/斜體版本的字體

如果(無論出於何種原因)您沒有單獨的粗體版本的字體,則使字體變粗的一個相當笨拙的解決方案是多次打印相同的文本並帶有輕微偏移。

andaleMono = ImageFont.truetype(ANDALE_MONO_PATH,16)
text = "hello world"
mainOffset = (50,50)
xoff, yoff = mainOffset
draw.text(mainOffset,text,font=andaleMono,fill='black')
draw.text((xoff+1,yoff+1),text,font=andaleMono,fill='black')
draw.text((xoff-1,yoff-1),text,font=andaleMono,fill='black')

許多字體為其粗體/斜體版本使用不同的 TTF 文件,所以我想如果您只指定該文件它會起作用。

嗯,這是我的第一條評論。 開始了。

我會盡力澄清程序。 起初我所做的是像這樣使用字體的“名稱”

font = ImageFont.truetype("C:\Windows\Fonts\\Arial Negrita.ttf",25)

但只有這樣的一些錯誤:

    Traceback (most recent call last):
  File "C:/Users/555STi/PycharmProjects/PIL/img.py", line 8, in <module>
    font = ImageFont.truetype("C:\Windows\Fonts\Arial negrita.ttf",25)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 262, in truetype
    return FreeTypeFont(font, size, index, encoding)
  File "C:\Python27\lib\site-packages\PIL\ImageFont.py", line 142, in __init__
    self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource

然后我想起有時字體有其他“名稱”或“文件名”,所以,我所做的是轉到字體文件夾,然后打開 Arial 字體,顯示所有樣式,如 negrita(粗體)、cursiva(斜體)等。

右鍵單擊“negrita”樣式,選擇“屬性”,然后出現字體的“真實姓名”。

就我而言,名字是“ariblk”

然后,最后,就這樣使用了這個名字。

font = ImageFont.truetype("C:\Windows\Fonts\\ariblk.ttf",25)

我知道這篇文章很舊,但今天幫助我找到了解決方案。 所以我希望能幫助任何人。

=)

到目前為止,還沒有粗體特征作為參數,但是您可以通過向具有相同文本顏色的文本添加筆划來輕松解決。 下一個代碼將詳細說明如何使用筆畫

    draw.text((x, y), text, fill=color, font=font, stroke_width=2,
          stroke_fill="black")

參考此處的其他答案,我對 Arial 粗體變體名稱的搜索產生了以下結果 (arialbd.ttf):

def FindFontsVariantsWithBase(fontBase="arial"):
        import matplotlib
        system_fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
        # for font in np.sort(system_fonts):
        #     print(font)
        fonts = np.sort(system_fonts).tolist()
        res = [i for i in fonts if fontBase in i]
        print(res)
        
FindFontsVariantsWithBase("arial")

['C:\WINDOWS\Fonts\arial.ttf', 'C:\WINDOWS\Fonts\arialbd.ttf', 'C:\WINDOWS\Fonts\arialbi.ttf', 'C:\WINDOWS\Fonts\arial. ttf', 'C:\Windows\Fonts\arial.ttf', 'C:\Windows\Fonts\arialbd.ttf', 'C:\Windows\Fonts\arialbi.ttf', 'C:\Windows\Fonts\ ariali.ttf'] (

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM