Advertisement
here2share

# smart_font_resize.py

Dec 31st, 2024 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. # smart_font_resize.py ZZZ note: actual font sizes seems too awkward
  2.  
  3. from PIL import ImageFont
  4. import os
  5.  
  6. text = "Hello Python World!"
  7. max_width = 600
  8.  
  9. def get_system_fonts():
  10.     font_dirs = [
  11.         "/usr/share/fonts",  # Linux
  12.         "/Library/Fonts",    # macOS
  13.         "C:/Windows/Fonts",  # Windows
  14.     ]
  15.    
  16.     fonts = []
  17.     for font_dir in font_dirs:
  18.         if os.path.exists(font_dir):
  19.             for root, _, files in os.walk(font_dir):
  20.                 for file in files:
  21.                     if file.endswith((".ttf", ".otf")):
  22.                         fonts.append(os.path.join(root, file))
  23.     return fonts
  24.  
  25. # system_fonts = get_system_fonts()
  26.  
  27. system_fonts = '''
  28. C:/Windows/Fonts/arial.ttf
  29. C:/Windows/Fonts/bahnschrift.ttf
  30. C:/Windows/Fonts/calibri.ttf
  31. C:/Windows/Fonts/Candara.ttf
  32. C:/Windows/Fonts/comic.ttf
  33. C:/Windows/Fonts/consola.ttf
  34. C:/Windows/Fonts/corbel.ttf
  35. C:/Windows/Fonts/cour.ttf
  36. C:/Windows/Fonts/Deng.ttf
  37. C:/Windows/Fonts/ebrima.ttf
  38. C:/Windows/Fonts/Gabriola.ttf
  39. C:/Windows/Fonts/gadugi.ttf
  40. C:/Windows/Fonts/georgia.ttf
  41. C:/Windows/Fonts/himalaya.ttf
  42. C:/Windows/Fonts/holomdl2.ttf
  43. C:/Windows/Fonts/impact.ttf
  44. C:/Windows/Fonts/Inkfree.ttf
  45. C:/Windows/Fonts/LeelawUI.ttf
  46. C:/Windows/Fonts/lucon.ttf
  47. C:/Windows/Fonts/Nirmala.ttf
  48. '''.strip().splitlines()
  49.  
  50. for font in system_fonts:
  51.     print(font)
  52.  
  53. print(f"Total fonts found: {len(system_fonts)}")
  54.  
  55. font_adj = []
  56.  
  57. for font_path in system_fonts:
  58.     min_size = 1
  59.     max_size = 1000
  60.     adjustment_history = [font_path]
  61.  
  62.     while min_size <= max_size:
  63.         mid_size = (min_size + max_size) // 2
  64.         label_font = ImageFont.truetype(font_path, mid_size)
  65.         text_width = label_font.getlength(text)
  66.         adjustment = max_width - text_width
  67.  
  68.         adjustment_history.append(mid_size)
  69.  
  70.         if adjustment > 0:
  71.             min_size = mid_size + 1
  72.         else:
  73.             max_size = mid_size - 1
  74.  
  75.     font_adj.append(adjustment_history)
  76.     print(adjustment)
  77.  
  78. for adj in font_adj:
  79.     print(adj)
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement