I recently found the need to scale some text to fit a certain area. However, because I am using multiple languages I have no idea how large the text string will be.
I could use
SetTextMaxWidth() but the downside to that is that any text that is too large will split onto the line below.
Instead I could use
SetTextScissor() but that has the problem of cropping any text that doesn't fit.
Neither solution is desirable under every circumstance. It may be a better solution to set the size of the text to fit but if you don't know how big the text is then what size do you make it?
So, here is the answer: A function that will scale the text to fit a desired size.
function SetTextToFit( txtObj as integer, width as float, AdjustIfFits as integer)
size# = GetTextSize( txtObj )
if GetTextTotalWidth( txtObj ) < width
if AdjustIfFits = 0
exitfunction
endif
repeat
inc size#, 0.1
SetTextSize( txtObj, size# )
until GetTextTotalWidth( txtObj ) >= width
exitfunction
else
repeat
dec size#, 0.1
SetTextSize( txtObj, size# )
until GetTextTotalWidth( txtObj ) <= width
exitfunction
endif
endfunction
And here it is in a full project that you can copy/paste and run:
// Project: TextWidth
// Created: 2015-08-09
// set window properties
SetWindowTitle( "TextWidth" )
SetWindowSize( 1024, 768, 0 )
// set display properties
SetVirtualResolution( 1024, 768 )
SetOrientationAllowed( 1, 1, 1, 1 )
a = CreateText( "Random Text String" )
SetTextPosition( a, 10, 250 )
SetTextSize( a, 10 )
SetTextToFit( a, 400, 1 )
do
print( "Text Size : " + str(GetTextSize(a)) )
print( "Total Width : " + str(GetTextTotalWidth(a)) )
Sync()
loop
function SetTextToFit( txtObj as integer, width as float, AdjustIfFits as integer)
size# = GetTextSize( txtObj )
if GetTextTotalWidth( txtObj ) < width
if AdjustIfFits = 0
exitfunction
endif
repeat
inc size#, 0.1
SetTextSize( txtObj, size# )
until GetTextTotalWidth( txtObj ) >= width
exitfunction
else
repeat
dec size#, 0.1
SetTextSize( txtObj, size# )
until GetTextTotalWidth( txtObj ) <= width
exitfunction
endif
endfunction
Parameters
txtObj - A previously created text object
width - The screen width to fit the text into
AdjustIfFits - A boolean. If TRUE(1) then the text will be scaled up to adjust it to the 'width' parameter. If False(0) then the text will not be scaled if it already fits within the required width but is smaller.
Because the function contains a loop I wouldn't recommend using it in real-time but it is perfect for setting up a HUD before a game.
Here is an example from my current project which demonstrates why I needed it.
[Edit] I'v just realised that this might have been better posted in the "
Useful community Functions" thread. So I have posted it there too.
AGK V2 user - Tier 1 (mostly)