Last active
June 4, 2021 13:28
-
-
Save azoyan/4653f8ff60e669914253a91c9600c24a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function CreateAutoSizedFont(width, height, str, fontName, baseSize, mode) | |
mode = "fast" | |
local k = 1.5 | |
local fontCache = {} | |
local font = graphics.newFont(fontName, baseSize) | |
fontCache[baseSize] = font | |
local incops = 1 | |
local decops = 0 | |
local textHeight = font:getHeight() | |
local wrappedWidth, wrappedtext = font:getWrap(str, width) | |
local textWidth = font:getWidth(str) | |
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 = graphics.newFont(fontName, baseSize) | |
incops = incops + 1 | |
fontCache[baseSize] = font | |
else | |
font = fontCache[baseSize] | |
end | |
textHeight = font:getHeight() | |
textWidth = font:getWidth(str) | |
wrappedWidth, wrappedtext = font:getWrap(str, width) | |
needIncrease = #wrappedtext == 1 and (textHeight < height / 1.5 or textWidth < width / 1.5) | |
needDecrease = textWidth > width or textHeight > height or #wrappedtext > 1 | |
print("needIncrease", needIncrease, baseSize, wrappedWidth, textWidth, width, textHeight, height, #wrappedtext, | |
mode) | |
end | |
while needDecrease do | |
baseSize = mode == "fast" and baseSize / k or baseSize - 1 | |
baseSize = math.ceil(baseSize) | |
if fontCache[baseSize] == nil then | |
font = graphics.newFont(fontName, baseSize) | |
decops = decops + 1 | |
fontCache[baseSize] = font | |
else | |
font = fontCache[baseSize] | |
end | |
textHeight = font:getHeight() | |
textWidth = font:getWidth(str) | |
wrappedWidth, wrappedtext = font:getWrap(str, width) | |
needDecrease = textWidth > width or textHeight > height or #wrappedtext > 1 | |
print("needDecrease", needDecrease, baseSize, wrappedWidth, textWidth, width, textHeight, height, #wrappedtext, | |
mode) | |
end | |
print("incops:", incops, "decops:", decops) | |
return font | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment