Last active
February 14, 2024 20:33
-
-
Save EngineerSmith/0220a2bc679c34cb1b92f9919cea7be3 to your computer and use it in GitHub Desktop.
Adds color back into text wrapped by font:getWrap
This file contains hidden or 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
getWrapColored = function(font, text, limit) | |
local width, wrappedText = font:getWrap(text, limit) | |
local wrappedTextColored, textIndex = { }, 1 | |
local currentColoredText, color = text[textIndex+1], text[textIndex] | |
for i, line in ipairs(wrappedText) do -- for each line | |
wrappedTextColored[i] = { } | |
while true do | |
-- if line fits within the current color string | |
if #line <= #currentColoredText then | |
table.insert(wrappedTextColored[i], color) | |
table.insert(wrappedTextColored[i], line) | |
currentColoredText = currentColoredText:sub(#line+1) | |
if currentColoredText == "" then | |
textIndex = textIndex + 2 | |
if textIndex > #text then | |
goto exit | |
end | |
currentColoredText, color = text[textIndex+1], text[textIndex] | |
end | |
break | |
else -- if line is greater than current color string | |
local before = line:sub(1, #currentColoredText) | |
table.insert(wrappedTextColored[i], color) | |
table.insert(wrappedTextColored[i], before) | |
line = line:sub(#currentColoredText+1) | |
textIndex = textIndex + 2 | |
if textIndex > #text then | |
goto exit | |
end | |
currentColoredText, color = text[textIndex+1], text[textIndex] | |
end | |
end | |
end | |
::exit:: | |
return width, wrappedTextColored | |
end | |
local lg = love.graphics | |
local font = lg.getFont() | |
--[[ | |
foo bar | |
jim jam | |
big big | |
]] | |
local coloredText = { | |
{1,0,0}, "foo ", | |
{0,1,0}, "bar jim ", | |
{0,0,1}, "jam ", | |
{1,0,1}, "big big ", | |
} | |
local width, wrappedText = getWrapColored(font, coloredText, font:getWidth("foo bar ")) | |
love.draw = function() | |
for i, line in ipairs(wrappedText) do | |
lg.print(line, 0, font:getHeight()*(i-1)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment