Created
July 30, 2025 13:42
-
-
Save YuriSizov/88464b9f26736900e90c67f6a9c4e926 to your computer and use it in GitHub Desktop.
UI Container that scales children to fit them
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
@tool | |
class_name ScaleFitContainer extends Container | |
var _children_scale_factor := 1.0 | |
func _notification(what: int) -> void: | |
if what == NOTIFICATION_SORT_CHILDREN: | |
_sort_children() | |
func _sort_children() -> void: | |
var parent_box := Rect2() | |
parent_box.size = size | |
for child in get_children(): | |
if child is not Control: | |
continue | |
var control := child as Control | |
if control.top_level || not control.is_visible_in_tree(): | |
continue | |
fit_child_in_rect(control, parent_box) | |
control.scale = Vector2(_children_scale_factor, _children_scale_factor) | |
func _get_minimum_size() -> Vector2: | |
var content_size := Vector2.ZERO | |
for child in get_children(): | |
if child is not Control: | |
continue | |
var control := child as Control | |
if control.top_level || not control.is_visible_in_tree(): | |
continue | |
var child_size := control.get_combined_minimum_size() | |
content_size.x = maxf(content_size.x, child_size.x) | |
content_size.y = maxf(content_size.y, child_size.y) | |
_children_scale_factor = 1.0 | |
if custom_minimum_size.x > 0.0: | |
_children_scale_factor = minf(_children_scale_factor, custom_minimum_size.x / content_size.x) | |
if custom_minimum_size.y > 0.0: | |
_children_scale_factor = minf(_children_scale_factor, custom_minimum_size.y / content_size.y) | |
var min_size := content_size * _children_scale_factor | |
return min_size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Godot_v4.3-stable_win64_2025-07-30_15-40-14.mp4