Jump to content

Calculation of text scaled down to fit inside a rectangle (postrender)

Recommended Posts

I want to make a password pad to put in some numbers.

The attached picture is what it looks now, at a resolution of 1080 p. (for 1920 p the green text fits in properly)




But as you can see the text is not scaled with the window, so how do I make it right?

I can get the top left and bottom right of the screen as x,y vectors, but how do i calculate that the text always is inside of it ?

Share this post

Link to post

I have decided to scale the font in percentage compared to the default size where the numbers are lining up.

it looks like this now : (it is the fastes way i could think of so its not optimized)


local windowres=Window:GetCurrent():GetWidth()

local optimFontSize= 65

local difference=0

if windowres~=1920 then --then it calculates optimal font resolution

System:Print(tostring("Calculating font optimized for Screen Resolution : "..windowres))


if windowres < 1920 then

difference = 1920-windowres


difference = windowres -1920



if difference~=0 then

optimFontSize = (100*difference)/1920

System:Print(tostring("Font is being Scaled (in %) : "..optimFontSize))


--optimFontSize is the percentage to add or decrease the font size




Share this post

Link to post

I've been thinking about this for my UI library. It's an awkward problem that I've not found a perfect solution for but this might work for your use case.The following function will determine a font height so that it will fit in a box defined by w and h. It will start with the font at max size, if the text goes beyond the defined width, it will reduce the font size to fit.


It loads a font every time you call it so I would call it only when text changes.


function FontFit(fontpath, text, w, h)
local font = Font:Load(fontpath, h)

textwidth = font:GetTextWidth(text)
if textwidth > w then
 return h * (w / textwidth)
 return h


An example of loading a font that will fit some_text that will fit in an area of 100x30

local FontHeight = FontFit("Fonts/arial.ttf", some_text, 100, 30)
local font = Font:Load("Fonts/arial.ttf", FontHeight)

Edited by thehankinator

Share this post

Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...