adjust/resize font in a label

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PositiverHeld

I would like to adjust the font size in a label so that the entire text is always displayed. My first approach was to simply count the lines and determine the size. If the size is then larger as the label I wanted to reduce the font size.

If I start with

label.get_visible_line_count()

I always get an outdated value back.

I set the text with :

label.text = str_text

or

label.set_text( str_text)

Am grateful for any tips and tricks, even if there is still a more elegant method for my problem. :wink:

Thx and cya Thommy

:bust_in_silhouette: Reply From: LoneDespair
# Make a dedicated class, so you don't have to write this code again, (Didn't test this, but should be able to give the idea)
# This will overwrite the labels font data so you would need to add support for things like colors and etc

# Adding this line, enables tool, which allows your changes to reflect within editor, without having to run the game, but can cause funny things and even crash the editor when used incorrectly
tool

class_name ResizableLabel

extends Label

const FONT_FALLBACK := preload("path to any font")
const PROPERTY_FONT := "custom_fonts/font"

export var size := 16 setget set_size
export var font := FONT_FALLBACK setget set_font

func _init() -> void:
  _resize()

func set_size(new_size : int) -> void:
  size = new_size
  _resize()

func set_font(new_font : DynamicFontData) -> void:
  font = new_font if new_font else FONT_FALLBACK
  _resize()

func _resize() -> void:
  var dynamic_font := DynamicFont.new()
  dynamic_font.font_data = font
  dynamic_font.size = size
  set(PROPERTY_FONT, dynamic_font)

# You can now see and instance this class through "Create new node" popup and be able to reuse it, just like built in nodes

Although this approach is quite unconventional, would suggest trying to use autowrap and scroll container, for really long texts

Or setting a dedicated size and a maximum amount of texts

Or line edit/text edit for inputs

I’ll try it right now and let you know if it worked.
Thank you and best regards from Hamburg

cya Thommy

PositiverHeld | 2021-02-21 17:08