I’m aware this is an old post, however, I have coded a solution for this problem. You can use the following 2 functions to solve your issue:
local DefaultTextSize = 90
local function CalculateSuitableTextSize(mainObject)
-- Set max size to default text size
local maxSize = DefaultTextSize
-- Loop through each object
for _, object in pairs(mainObject:GetDescendants()) do
-- Return if not text label
if not object:IsA("TextLabel") then continue end
local textLabel: TextLabel = object
local textBounds = textLabel.TextBounds
local absoluteSize = textLabel.AbsoluteSize
-- If text fits in box, then continue. TextFits property can be used here as an alternative
if textBounds.X < absoluteSize.X then continue end
-- If does not fit, then calculate text max size
local percentageToShrink = absoluteSize.X / textBounds.X
local newTextSize = textLabel.TextSize * percentageToShrink
-- Set new max text size
if newTextSize > maxSize then continue end
maxSize = newTextSize
end
return maxSize
end
local function SetTextSizeForAllTextLabels(mainObject, textSize)
for _, object in pairs(mainObject:GetDescendants()) do
if not object:IsA("TextLabel") then continue end
local textLabel: TextLabel = object
textLabel.TextSize = textSize
end
end
mainObject can be anything, however, should have all the text labels you want to be the same size. The “CalculateSuitableTextSize” function returns the size that all text labels can fit in.
Then you can the “SetTextSizeForAllTextLabels” with the text size that the previous functions returned. This will set all the text labels to the same size
Here’s the logic behind the maths:
Let’s say the following are the properties of the text label:
- AbsoluteSize.X = 50
- TextBounds.X = 100
- TextSize = 90
This means that the text takes up 100 pixels, but the text label can only fit 50. So you need to work out the percentage of how much you need to shrink the text bound box. To do this, you do:
- AbsoluteSize.X / TextBounds.X = PercentageToShrink
- Answer: 50 / 100 = 0.5
Then you apply that percentage decrease to the text size:
- TextSize * PercentageToShrink = NewTextSize
- 90 * 0.5 = 45
Finally, you check if the NewTextSize is smaller than the current SmallestTextSize. If it is, then set SmallestTextSize to equal NewTextSize. Example:
- SmallestTextSize = 50
- NewTextSize = 45
- Since 45 is smaller than 50, then set SmallestTextSize to 45
NOTE:
- This code only checks the X axis, however, feel free to adjust it to your needs.
- Text Scaled needs to be disabled, however, you can set the default text size to max size and these 2 functions should scale the text down
- To automatically scale the GUI when screen size changes, you’ll need to call these 2 functions whenever GUI.Changed event is called. If this does not work, you can also try RunService.Heartbeat