Having a hard time dynamically changing textbox size based on screen size and textbox content

As the title describes, I’m writing a function that automatically resizes a textbox based on the text inside of it and the player’s screen size. The text is a constant size and font. I’m essentially trying to do what Roblox did with their chat system where the chatbox resizes whenever the player resizes their screen (if needed) or text won’t fit on the current line. This is what I have so far:

local function resizeChatbox(property)
	local frame = TextService:GetTextSize(chatBox.Text, 13, Enum.Font.Gotham, Vector2.new(2000, 13))
	if property == "Text" or property == "AbsoluteSize" then
		if not chatBox.TextFits or chatBox.TextBounds.Y < chatBox.AbsoluteSize.Y and not sizeChangeInProgress then
			sizeChangeInProgress = true
			wait()
			local frame = TextService:GetTextSize(chatBox.Text, 13, Enum.Font.Gotham, Vector2.new(2000, 13))
			local textLines
			if frame.X == 0 then
				textLines = 1
			else
				textLines = math.ceil(frame.X/chatBox.TextBounds.X)
			end
			local chatSize = 13 * textLines
			chatBox.Size = UDim2.new(.8, 0, 0, chatSize)
			chatBox.Position = UDim2.new(.1, 0, 1, -10 - chatSize)
			chatBoxBorder.Position = UDim2.new(0, 0, 1, -22 - chatSize)
			sizeChangeInProgress = false
		end
	end
end

This works decently well. However, sometimes text will go off the textbox (and therefore not render) if it’s created after line 1. I believe this is because “frame” doesn’t have the spaces in the text caused by a single word forcing the textbox to create a new line. I’m not sure how to change my code to account for this.
Of course, please feel free to suggest a better method for achieving what I’m trying to achieve. :slight_smile:

A suggested better method I would have is avoid scripting it.

You can already resize a TextBox based on Screen size relatively easily and get the font to adjust, if you make your GUIs using scale instead of offset and by using a UIAspectRatioConstraint.

You can also make the text the correct size by scaling it and by text wrapping it, and combat different screen sizes by having a UISizeConstraint.

I made a fairly detailed post about this in a response to a reply a while back: How can i properly position UI - #5 by Alexander_Ashford

1 Like

Thanks for the reply and the link. I would like to keep the font size constant, though. This is what I’m trying to achieve.

4 Likes