Fixed width for label calculated by character length

Godot Version

4.4.1

Question

I want to fix my label width for whatever 10 character long is for given font.
Even label string length is 3 chars, i want it to have 10 character long width. How to achieve that?

I have an utility method like below

func calculate_string_width(_str:String, font_size:float, horizontal_alignment:int = HORIZONTAL_ALIGNMENT_CENTER) -> float:
	return Constants.MAIN_FONT.get_string_size(_str, horizontal_alignment, -1, font_size).x

After changing label text, width is changed even i set the fixed width after that.

but why would you want that if Godot can do that automatically ? it is a built in feature of the Label node

Even label string length is 3 chars, i want it to have 10 character long width

That’s actually impossible to correctly predict a width of an unknown string, unless you’re using a monospaced font like Courier.
See this example below, both of these strings are 10 characters long, but have a vastly different width:

  1. iiiiiiiiii
  2. wwwwwwwwww

In the monospaced font, both of these would have the same width:

1. iiiiiiiiii
2. wwwwwwwwww

I think you need to pivot your idea to something else. If you gave us a bit more context of your issue, what you’re exactly trying to achieve, including some screenshots and whatnot, maybe we can help you decide the best course of action.

maybe you can achieve it by adjusting this field

and setting the min width and height to 0 (within the layout section)

Sorry why i want this feature, let me show you,
ss1
ss2
I need this for a countdown label with bordered background. And the width is jiggling, wobbling 3-5 pixel for each frame which is a disturbing look.

Either use a monospace font, or make a Label for each character with a fixed width, filling each label with a single character from the string via script.

1 Like

to skip complexity → have you tried setting the min width to the size which doesn’t wobble ? … basically making the min width the widest possible case.