Code: Select all
function CreateAutoSizedFont(width, height, str, fontName, baseSize, mode)
mode = "fast"
local k = 1.5
local font = love.graphics.newFont(fontName, baseSize)
local fontCache = {}
fontCache[baseSize] = font
local textHeight = font:getHeight()
local textWidth, wrappedtext = font:getWrap(str, width)
local needIncrease = #wrappedtext == 1 and (textHeight < height / 1.5 or textWidth < width / 1.5)
local needDecrease = textHeight > height or #wrappedtext > 1
while needIncrease and not needDecrease do
baseSize = mode == "fast" and baseSize * k or baseSize + 1
baseSize = math.floor(baseSize)
if fontCache[baseSize] == nil then
font = love.graphics.newFont(fontName, baseSize)
fontCache[baseSize] = font
else
font = fontCache[baseSize]
end
textHeight = font:getHeight()
textWidth, wrappedtext = font:getWrap(str, width)
needIncrease = #wrappedtext == 1 and (textHeight < height / 1.5 or textWidth < width / 1.5)
needDecrease = textHeight > height or #wrappedtext > 1
end
while needDecrease do
baseSize = mode == "fast" and baseSize / k or baseSize - 1
baseSize = math.ceil(baseSize)
if fontCache[baseSize] == nil then
font = love.graphics.newFont(fontName, baseSize)
fontCache[baseSize] = font
else
font = fontCache[baseSize]
end
textHeight = font:getHeight()
textWidth, wrappedtext = font:getWrap(str, width)
needDecrease = textHeight > height or #wrappedtext > 1
end
return font
end
I need to increase or decrease font depending on the specified dimensions.
The main problem is that the font is re-created every time it needs to be increased / decreased, because the slow operation love.graphics.newFont() is called. Is there a way to find size of text without recreating font?
In this version I use the local cache to avoid creating the font if the font with the given size has already been created
Of course, I understand that this operation is performed once per game and the font will be globally saved. But I hope we have an alternative way or a better algorithm.
What about the best practices for this?