11import drawSvg as draw
22import colorsys
3+ import numpy as np
34import os
45from PIL import ImageFont
56
@@ -85,6 +86,35 @@ def _findSpace(words, width, height, maxFontSize):
8586 size = min (maxFontSize , fitTextHeight , fitTextWidth )
8687 return size
8788
89+
90+ def _find_breaks (num_spaces , num_breaks = 3 ):
91+ """
92+ INTERNAL: Generate break mapping
93+
94+ :param num_spaces: number of spaces in string
95+ :param num_breaks: number of breaks to insert
96+ :return: list of possible break mappings
97+ """
98+ breaks = set ()
99+
100+ def recurse (breakset_inherit , depth , num_breaks ):
101+ """recursive combinatorics; breakset is binary array of break locations; depth is the depth of recursion,
102+ num_breaks is how many breaks should be added"""
103+ for i in range (len (breakset_inherit )): # for each possible break
104+ # insert a break here
105+ breakset = np .copy (breakset_inherit )
106+ breakset [i ] = 1
107+ breaks .add ("" .join (str (x ) for x in breakset ))
108+ # try inserting another depth of break
109+ if depth < num_breaks - 1 : recurse (breakset , depth + 1 , num_breaks )
110+
111+ initial_breaks = [0 ] * num_spaces
112+ breaks .add ("" .join (str (x ) for x in initial_breaks ))
113+ recurse (initial_breaks , 0 , num_breaks )
114+
115+ return breaks
116+
117+
88118def _optimalFontSize (st , width , height , maxFontSize = 12 ):
89119 """
90120 INTERNAL: Calculate the optimal fontsize and word layout for a box of width x height
@@ -98,10 +128,16 @@ def _optimalFontSize(st, width, height, maxFontSize=12):
98128 words = st .split (" " )
99129 bestSize = - 9999
100130 bestWordArrangement = []
101- for j in range (0 , 2 ** (len (words ) - 1 )):
131+
132+ num_spaces = len (words )
133+ num_breaks = 1
134+ if num_spaces < 20 :
135+ num_breaks = 2
136+ elif num_spaces < 50 :
137+ num_breaks = 3
138+ breaks = _find_breaks (num_spaces , num_breaks )
139+ for binaryString in breaks :
102140 wordSet = []
103- construct = "{0:0" + str (len (words )) + 'b}'
104- binaryString = construct .format (j )
105141
106142 for k in range (0 , len (binaryString )):
107143 if binaryString [k ] == "0" :
@@ -266,7 +302,10 @@ def build(height, width, label, config, variant='text', t1text=None, t2text=None
266302 cells .append (cell )
267303 tblob = str (entry [1 ])
268304 off = (block_width - (5 * (1 + len (tblob ))))/ 2
269- label = Text (tblob , 12 , ctype = 'label' , ty = 25 , tx = off )
305+ if off < 0 :
306+ off = 0
307+ fs , _ = _optimalFontSize ("0" , width / len (colors ), height )
308+ label = Text (tblob , fs , ctype = 'label' , ty = 25 , tx = off )
270309 cell .append (label )
271310 return g
272311
0 commit comments