How to get width of a truetype font character in 1200ths of an inch with Python?

后端 未结 2 2027
广开言路
广开言路 2021-02-06 14:01

I can get the height and width of a character in pixels with PIL (see below), but (unless I\'m mistaken) pixel size depends on the screen\'s DPI, which can vary. Instead what I\

2条回答
  •  星月不相逢
    2021-02-06 14:18

    This worked better for me:

    def pixel_width(unicode_text): 
        width=len(unicode_text)*50 
        height=100 
        back_ground_color=(0,0,0) 
        font_size=64 
        font_color=(255,255,255) 
    
        im  =  Image.new ( "RGB", (width,height), back_ground_color ) 
        draw  =  ImageDraw.Draw (im) 
        unicode_font = ImageFont.truetype("./usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", font_size) 
        draw.text ( (0,0), unicode_text, font=unicode_font, fill=font_color ) 
        im.save("/dev/shm/text.png") 
        box = Image.open("/dev/shm/text.png").getbbox() 
        return box[2] - box[0] 
    

提交回复
热议问题