Trying to set size of a text label to TextBounds.X, though it is returning the incorrect information

I want a text label that automatically resizes based on text length. This works, but for some reason only with the Gotham font. I want to add font changing to my module, but this has stopped me. For example:

When using the SpecialElite font, the text goes outside the text label, but the TextBounds only return the size for the Gotham font. Can someone help with this please?

Sizing:

label.Size = UDim2.new(0, math.max(7, label.TextBounds.X + 23), 0, 30)

Try using TextService:GetTextSize to get the text bounds, instead of using TextBounds.

I know I could do this, but thing is I don’t want to use GetTextSize.

That’s unfortunate. I’m pretty sure it’s the right solution to your problem. Good luck!

I tried using it. But I am kind of confused about the last argument. What does it do exactly? Thanks in advance.

local TextService = game:GetService("TextService")
local TextSize = TextService:GetTextSize(label.Text, label.TextSize, label.Font, ???).X

It’s the max size of the frame, which is useful if you want your text to wrap after a certain size.

If you want it to always be one line, you can set the size to be huge:

local str = label.Text -- or whatever
local fontSize = label.TextSize
local font = label.Font
local size = Vector2.new(math.huge, math.huge)
local bounds = game:GetService("TextService"):GetTextSize(str, fontSize, font, size)

label.Size = UDim2.fromOffset(bounds.X, bounds.Y)

Wait so if enable text truncating on the label, the text wont go outside the max size? (if text wrappping is disabled as well.)

Not quite

GetTextSize with a huge size is asking: “given this font, and with an infinite amount of room to expand without wrapping, how big would the text theoretically be?”

It will be accurate if the text on the label also doesn’t wrap.

Vector2.new(0, 0) or even Vector2.new() has the same effect as explicitly passing math.huge twice.

1 Like