Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjusting date time text to match image size #22

Merged
merged 14 commits into from
May 21, 2024
22 changes: 20 additions & 2 deletions geogif/gif.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,24 @@ def gif(
time_coord = arr[arr.dims[0]]
labels = time_coord.dt.strftime(date_format).data

fnt = ImageFont.load_default()
# default font size to start
fontsize = 6

# load up default font
fnt = ImageFont.load_default(size = fontsize)

# grab first label and image to test
test_label, test_img = labels[0], imgs[0]

# this could be a user defined value
img_fraction = 0.1

# increment font until you get large enough font
while fnt.getbbox(test_label)[2] < img_fraction*test_img.size[0]:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Pillow docs say this controls "The font size of Aileron Regular"—so if you don't have FreeType support and get the basic bitmap font (like previous versions of Pillow had), I think this would loop forever, since the font would never actually get bigger no matter what font size you asked for!

# iterate until the text size is just larger than the criteria
fontsize += 1
fnt = ImageFont.load_default(fontsize)

for label, img in zip(labels, imgs):
# get a drawing context
d = ImageDraw.Draw(img)
Expand All @@ -230,7 +247,8 @@ def gif(
x = width - t_width - offset

if date_bg:
d.rectangle((x, y, x + t_width, y + t_height), fill=date_bg)
# added a 1.6 ratio increase for height to ensure text is fully covered
d.rectangle((x, y, x + t_width, y + t_height * 1.6), fill=date_bg)
# draw text
d.multiline_text((x, y), label, font=fnt, fill=date_color)

Expand Down