@@ -209,13 +209,15 @@ def DisplayText(
209209 text : str ,
210210 x : int = 0 ,
211211 y : int = 0 ,
212+ width : int = 0 ,
213+ height : int = 0 ,
212214 font : str = "roboto-mono/RobotoMono-Regular.ttf" ,
213215 font_size : int = 20 ,
214216 font_color : Tuple [int , int , int ] = (0 , 0 , 0 ),
215217 background_color : Tuple [int , int , int ] = (255 , 255 , 255 ),
216218 background_image : str = None ,
217219 align : str = 'left' ,
218- anchor : str = None ,
220+ anchor : str = 'lt' ,
219221 ):
220222 # Convert text to bitmap using PIL and display it
221223 # Provide the background image path to display text with transparent background
@@ -249,12 +251,30 @@ def DisplayText(
249251 self .font_cache [(font , font_size )] = ImageFont .truetype ("./res/fonts/" + font , font_size )
250252 font = self .font_cache [(font , font_size )]
251253 d = ImageDraw .Draw (text_image )
252- left , top , right , bottom = d .textbbox ((x , y ), text , font = font , align = align , anchor = anchor )
253254
254- # textbbox may return float values, which is not good for the bitmap operations below.
255- # Let's extend the bounding box to the next whole pixel in all directions
256- left , top = math .floor (left ), math .floor (top )
257- right , bottom = math .ceil (right ), math .ceil (bottom )
255+ if width == 0 or height == 0 :
256+ left , top , right , bottom = d .textbbox ((x , y ), text , font = font , align = align , anchor = anchor )
257+
258+ # textbbox may return float values, which is not good for the bitmap operations below.
259+ # Let's extend the bounding box to the next whole pixel in all directions
260+ left , top = math .floor (left ), math .floor (top )
261+ right , bottom = math .ceil (right ), math .ceil (bottom )
262+ else :
263+ left , top , right , bottom = x , y , x + width , y + height
264+
265+ if anchor .startswith ("m" ):
266+ x = (right + left ) / 2
267+ elif anchor .startswith ("r" ):
268+ x = right
269+ else :
270+ x = left
271+
272+ if anchor .endswith ("m" ):
273+ y = (bottom + top ) / 2
274+ elif anchor .endswith ("b" ):
275+ y = bottom
276+ else :
277+ y = top
258278
259279 # Draw text onto the background image with specified color & font
260280 d .text ((x , y ), text , font = font , fill = font_color , align = align , anchor = anchor )
0 commit comments