Last active
October 11, 2023 17:44
-
-
Save Grunerd/68be59e3bf579b1cbe4cf149a32aa917 to your computer and use it in GitHub Desktop.
LabelFontScaler for Control Node in Godot 4
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
extends Control | |
# ensure that you attach this script to the parent node of your ui elements | |
# ensure that you link the signal "resize" of this control node to this script | |
# | |
@export_enum("Horizontal","Vertical") var scaleMode = "Vertical" | |
# cache for all labels and ther initial font size | |
var labels:Array[Label] | |
var labels_dict:Dictionary | |
var initialScreenSize:Vector2i | |
func _ready(): | |
initialScreenSize = get_viewport_rect().size | |
get_child_labels(self) | |
# fills label cache with references and their font size | |
func get_child_labels(node:Node): | |
if node is Label: | |
var label = node as Label | |
if not label.label_settings == null: | |
labels.append(label) | |
labels_dict[label] = label.label_settings.font_size | |
if node.get_child_count()>0: | |
for child in node.get_children(): | |
get_child_labels(child) | |
# calculates new font size and adjusts it to all labels reference in cache | |
func adjust_child_labels(currentScreenSize:Vector2i): | |
for label in labels: | |
var scale:float | |
if(scaleMode == "Vertical"): | |
scale = labels_dict[label] as float / initialScreenSize.y as float * currentScreenSize.y as float | |
else: | |
scale = labels_dict[label] as float / initialScreenSize.x as float * currentScreenSize.x as float | |
label.label_settings.font_size = scale | |
# only execute on resize | |
func _on_resized() -> void: | |
adjust_child_labels(get_viewport_rect().size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment