YouTip LogoYouTip

Pillow Imagedraw Textbbox

The textbbox() method is a very useful function in the ImageDraw module, used to calculate the bounding box occupied by a given text when drawing it on an image. The textbbox() method does not actually draw the text, but returns the coordinates of the rectangular area that the text will occupy. ### Method Syntax textbbox(xy, text, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0) * * * ### Parameter Details #### 1. xy (Required) * **Type**: Tuple (x, y) * **Description**: Specifies the starting coordinate position of the text * **Note**: The actual text position is also affected by the anchor parameter #### 2. text (Required) * **Type**: String * **Description**: The text content for which to calculate the bounding box #### 3. font (Optional) * **Type**: ImageFont object * **Default**: None (uses default font) * **Description**: Specifies the font to use for the text #### 4. anchor (Optional) * **Type**: String * **Default**: None (equivalent to "la") * **Description**: Controls the text alignment relative to the xy coordinate * **Common values**: * "la": Left align, baseline align (default) * "lt": Left align, top align * "ma": Center align, baseline align * "mm": Fully centered (horizontal and vertical) #### 5. spacing (Optional) * **Type**: Integer * **Default**: 4 * **Description**: Line spacing for multi-line text #### 6. align (Optional) * **Type**: String * **Default**: "left" * **Description**: Alignment of multi-line text ("left", "center", "right") #### 7-10. Other Advanced Parameters * Parameters such as `direction`, `features`, `language`, and `stroke_width` are used to control advanced text rendering features, and beginners usually don't need to master them immediately. ### Return Value The textbbox method returns a 4-tuple (left, top, right, bottom), representing the bounding box coordinates of the text. * * * ## Practical Application Examples ### Example 1: Basic Usage ## Instance from PIL import Image, ImageDraw, ImageFont # Create a blank image image = Image.new('RGB',(400,200),'white') draw = ImageDraw.Draw(image) # Load font font = ImageFont.truetype('arial.ttf',24) # Calculate text bounding box bbox = draw.textbbox((50,50),"Hello Pillow!", font=font) print("Text bounding box:", bbox)# Output: (left, top, right, bottom) # Draw bounding box (visualization) draw.rectangle(bbox, outline='red') # Actually draw the text draw.text((50,50),"Hello Pillow!", font=font, fill='black') image.show() ### Example 2: Using anchor Parameter ## Instance # Continue using the image and draw objects above # Center point coordinates center_x, center_y =200,100 # Calculate centered text bounding box bbox = draw.textbbox((center_x, center_y),"Centered", font=font, anchor="mm") print("Centered bounding box:", bbox) # Draw center point and bounding box draw.rectangle(bbox, outline='blue') draw.ellipse([(center_x-2, center_y-2),(center_x+2, center_y+2)], fill='green') # Draw text draw.text((center_x, center_y),"Centered", font=font, fill='black', anchor="mm") image.show() * * * ## Common Application Scenarios 1. **Text Layout Calculation**: Determine the space occupied by text before drawing 2. **Automatic Line Wrapping**: Calculate how text wraps based on available width 3. **Text Centering**: Achieve precise centering combined with bounding box calculation 4. **Collision Detection**: Prevent text from overlapping with other elements * * * ## Notes 1. **Font Impact**: Different fonts may return very different bounding box sizes 2. **Multi-line Text**: For multi-line text, the bounding box will include all lines 3. **Performance Consideration**: Frequent calls may affect performance, it is recommended to cache results 4. **Accuracy**: Bounding box calculation is approximate, actual rendering may vary slightly * * * ## Comparison with textsize In older versions of Pillow, the textsize method was commonly used to get text dimensions, but that method has been deprecated. textbbox provides more precise information (not only width and height, but also position information), and is the preferred method for new code. ## Instance # Old method (not recommended) width, height = draw.textsize("Text", font=font) # New method (recommended) left, top, right, bottom = draw.textbbox((0,0),"Text", font=font) width = right - left height = bottom - top * * * ## Summary The ImageDraw.textbbox method is a powerful and practical tool in the Pillow library, especially suitable for scenarios requiring precise control of text layout. By understanding its parameters and return values, developers can easily implement various complex text layout requirements.
← Pillow Imageops ModulePillow Imagefont Module β†’