Now I write python function which adds image on the background and also adds text in…
- User
Now I write python function which adds image on the background and also adds text in specific area on this background. Sometimes text is too long to fit specific area, therefore I need that you modify this function so that it automatically adjusted the font size, trying to use the largest possible font size (no more than 200) in order to fill as much of the specified area as possible, while staying within its limits. I'm sure that you will be use pillow libary, therefore when you try calculate text size use textbbox() function instead of textsize().
Code: from PIL import Image, ImageDraw, ImageFont, ImageOps import textwrap import random
def draw_text(draw, text, font, default_text_color, text_area_width, text_area_height, start_x, start_y, shadow_color, shadow_offset, line_spacing, color_ratio=0.2, alternate_color='orange'): text = text.upper() words = text.split()
Determine the number of words to color differently, based on color_ratio
num_words_to_color = max(1, int(len(words) * color_ratio))
Randomly pick unique words to color differently
words_to_color = set(random.sample(words, num_words_to_color))
lines = textwrap.wrap(text, width=text_area_width // (font.size // 2))
Font metrics
ascent, descent = font.getmetrics()
Calculate the total height of the text block with additional line spacing
total_text_height = len(lines) * (ascent + descent) + (line_spacing * (len(lines) - 1))
Initial y offset - start at the vertical center with consistent line spacing
y_offset = start_y + (text_area_height - total_text_height) // 2
for line in lines: # Calculate the line width for horizontal centering line_width = sum(draw.textbbox((0, 0), word + ' ', font=font)[2] for word in line.split()) x_offset = start_x + (text_area_width - line_width) // 2
for word in line.split(): # Determine coordinates for the text and shadow shadow_x = x_offset + shadow_offset shadow_y = y_offset + shadow_offset word_color = alternate_color if word in words_to_color else default_text_color # Draw shadow first if shadow_offset: draw.text((shadow_x, shadow_y), word, font=font, fill=shadow_color) # Draw the word itself draw.text( (x_offset, y_offset), word, font=font, fill=word_color ) # Increment x_offset by the width of the word word_width = draw.textbbox((x_offset, y_offset), word, font=font)[2] - draw.textbbox((x_offset, y_offset), word, font=font)[0] space_width = draw.textbbox((0, 0), ' ', font=font)[2] x_offset += word_width + space_width # Increment y_offset by the line height (ascent + descent) plus the additional line spacing y_offset += ascent + descent + line_spacing if len(lines) > 1: y_offset += line_spacing # add additional space between lines if there's more than one line - Assistant