Word wrap
Uses natiny.font.measure_wrapped and natiny.render.text_box to keep the panel
and wrapped text at the same size. Move the mouse horizontally to change the
wrap width.
local natiny = require("natiny")
natiny.backend.init()
local win = natiny.window.create("Word wrap", 900, 600)
natiny.window.set_scale_mode(win, natiny.window.SCALE_MODE_STRETCH)
local font = natiny.font.create(natiny.resource.load("common/fonts/roboto.ttf"), 22)
local TEXT = "Word wrapping is measured by the same code that draws it, " ..
"so a panel sized with measure_wrapped is guaranteed to contain " ..
"what text_box puts inside it. Move the mouse."
local BG = natiny.color.from_hex("#151E2C")
local OBJECT = natiny.color.from_hex("#A9B3C5")
local ACCENT = natiny.color.from_hex("#F8F9FD")
local LIGHT_TEXT = natiny.color.from_hex("#F3F5FA")
local DARK_TEXT = natiny.color.from_hex("#111827")
local X, Y = 120, 160
natiny.backend.loop(function(dt)
natiny.window.bind(win, function()
local width = math.max(90, math.min(660, natiny.input.get_mouse_x() - X))
local w, h, lines = natiny.font.measure_wrapped(font, TEXT, width)
natiny.render.clear(BG)
natiny.render.set_color(OBJECT)
natiny.render.rectangle(X - 16, Y - 16, width + 32, h + 32)
natiny.render.set_color(ACCENT)
natiny.render.rectangle_outline(X - 16, Y - 16, width + 32, h + 32, 3)
natiny.render.set_color(ACCENT)
natiny.render.line(X + width, Y - 40, X + width, Y + h + 40, 1)
natiny.render.set_color(DARK_TEXT)
natiny.render.text_box(font, X, Y, width, h, TEXT)
natiny.render.set_color(LIGHT_TEXT)
natiny.render.text(font, X - 16, 80, string.format(
"wrap at %d -> %d lines, widest %.0f, %.0f tall", width, lines, w, h))
end)
end)
natiny.backend.shutdown()