Skip to content

Instantly share code, notes, and snippets.

@Khubajsn
Created April 29, 2013 15:21
Show Gist options
  • Select an option

  • Save Khubajsn/5482298 to your computer and use it in GitHub Desktop.

Select an option

Save Khubajsn/5482298 to your computer and use it in GitHub Desktop.
Garry's mod Lua - drawing multiline text.
local currentY = 50; -- the first line of text will be at Y coordinate 50
local textX = 50; -- what X coordinate will the text be drawn from
local maxWidth = 500; -- maximal width of the text, if the text exceeds this size then it'll be broken into another line(s)
surface.SetFont("SomeFontYouUse")
surface.SetTextColor(Color(255,255,255))
local function breakIntoLines(text, mWidth)
local wordsBuffer = {}
local lines = {}
for word in string.gmatch(text, " ") do -- iterate over words
local w, h = surface.GetTextSize(text)
if (w > mWidth) then
table.insert(lines, table.concat(wordsBuffer, " "))
wordsBuffer = ""
else
table.insert(wordsBuffer, word)
end
end
if (#wordsBuffer > 0) then
table.insert(lines, table.concat(wordsBuffer, " "))
end
return lines
end
local chatLines = {}
for textLine in string.gmatch(textToDraw, "\n") do
for brokenLine in pairs(breakIntoLines(textLine, maxWidth)) do
table.insert(chatLines, brokenLine)
end
end
for textLine in pairs(chatLines) do
local textLineWidth, textLineHeight = surface.GetTextSize(textLine)
surface.SetTextPos(textX, currentY)
surface.DrawText(textLine)
currentY = currentY + textLineHeight
end
@Phoenix1123
Copy link

Very useful. Updated and slightly modified version on my GitHub (11/05/19)
https://gist.github.com/Phoenix1123/95863a1a903f7d50ec68a2e86e34d5c7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment