* preview_image: dynamic size of "size" block

This commit is contained in:
Phil Zhitnikov 2023-07-22 21:27:42 +04:00
parent 367047d231
commit 91bdf4cd31
2 changed files with 12 additions and 7 deletions

View File

@ -4,7 +4,7 @@ from store.utils import create_preview
for i in range(1, 5):
order_id = f'result{i}'
image = create_preview(f'source{i}.jpeg',
size=40,
size='40 1/3',
price_rub=100.5,
title_lines=['New Balance', 'NB 9060'])

View File

@ -21,7 +21,7 @@ def create_preview(source_image: str, size=None, price_rub=None, title_lines=Non
font_path = os.path.join(BASE_DIR, 'static', 'preview_image_font.ttf')
return ImageFont.truetype(font_path, size=font_size)
def draw_text(xy: Tuple[float, float], text: str, font: ImageFont, multiline_width: int = None, fill: str = None):
def draw_text(xy: Tuple[float, float], text: str, font: ImageFont, multiline_width: int = None, **kwargs):
x, y = xy
block_width = 0
@ -35,7 +35,7 @@ def create_preview(source_image: str, size=None, price_rub=None, title_lines=Non
for line in text:
_, _, line_width, line_height = font.getbbox(line)
draw.text((x, y), line, font=font, fill=fill)
draw.text((x, y), line, font=font, **kwargs)
y += line_height
block_width = max(block_width, line_width)
@ -77,16 +77,21 @@ def create_preview(source_image: str, size=None, price_rub=None, title_lines=Non
if size:
size_text = str(size)
size_font = get_font(20)
size_padding = 7
_, _, line_width, line_height = size_font.getbbox(size_text)
rect_x, rect_y = hor_padding, title_y + 30
rect_width, rect_height = 40, 40
rect_width, rect_height = (line_width + size_padding * 2), (line_height + size_padding * 2)
rect_width, rect_height = max(40, rect_width), max(40, rect_height)
# size text is slightly inside a rect
size_x, size_y = rect_x + 7, rect_y + 7
size_x, size_y = (rect_x + rect_width/2), (rect_y + rect_height/2)
draw.rectangle((rect_x, rect_y, rect_x + rect_width, rect_y + rect_height), fill='black', width=2)
block_size = draw_text((size_x, size_y), size_text, font=size_font, fill='white')
left_block_width = max(left_block_width, max(block_size[0], rect_width))
draw_text((size_x, size_y), size_text, font=size_font, fill='white', anchor='mm')
left_block_width = max(left_block_width, rect_width)
# Draw price
if price_rub: