Created
December 15, 2025 19:35
-
-
Save bearlikelion/8d1c8b2b298cf2985595cfab63e69122 to your computer and use it in GitHub Desktop.
Auto resize font labels for Godot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func _get_autosize_font_size(label: Label, min_font_size: int = 8, max_font_size: int = 48) -> int: | |
| var aux_text := label.text | |
| var base_font := label.get_theme_font("font") | |
| var width_limit := size.x # will use control data for more accurate behavior | |
| var height_limit := size.y # will use control data for more accurate behavior | |
| var best_font_size := min_font_size | |
| # Will do a binary search for faster results | |
| var low := min_font_size | |
| var high := max_font_size | |
| while low <= high: | |
| var mid := int((low + high) * 0.5) # Test font size | |
| var text_size := base_font.get_multiline_string_size(aux_text, horizontal_alignment,\ | |
| width_limit, mid, max_lines) | |
| # WARNING for some reason is returning a wrong height while setting max line count | |
| # thus making max_lines != INFINITE_MAX_LINES unusable. | |
| var text_width := text_size.x | |
| var text_height := text_size.y | |
| # Will test size withouth waiting a frame draw. | |
| if text_width <= width_limit and text_height <= height_limit: | |
| best_font_size = mid | |
| low = mid + 1 # Try bigger | |
| else: | |
| high = mid - 1 # Try smaller | |
| label.add_theme_font_size_override("font_size", best_font_size) | |
| return best_font_size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment