Spacing and metrics
Visualizes measured text bounds, baselines, ascent, and descent while spacing changes. Use Up / Down for line spacing and Left / Right for letter spacing.
local natiny = require("natiny")
natiny.backend.init()
local win = natiny.window.create("Spacing and metrics", 900, 600)
natiny.window.set_scale_mode(win, natiny.window.SCALE_MODE_STRETCH)
local font = natiny.font.create(natiny.resource.load("data/common/fonts/roboto.ttf"), 34)
local SAMPLE = "Typography\nText layout"
local BG = { 21 / 255, 30 / 255, 44 / 255 } -- #151E2C
local OBJECT = { 169 / 255, 179 / 255, 197 / 255 } -- #A9B3C5
local ACCENT = { 248 / 255, 249 / 255, 253 / 255 } -- #F8F9FD
local LIGHT_TEXT = { 243 / 255, 245 / 255, 250 / 255 } -- #F3F5FA
local X, Y = 80, 180
local line_spacing, letter_spacing = 1.0, 0.0
natiny.backend.loop(function(dt)
natiny.window.bind(win, function()
if natiny.input.get_key_down(natiny.input.KEY_UP) then line_spacing = line_spacing + dt end
if natiny.input.get_key_down(natiny.input.KEY_DOWN) then line_spacing = line_spacing - dt end
if natiny.input.get_key_down(natiny.input.KEY_RIGHT) then letter_spacing = letter_spacing + dt * 12 end
if natiny.input.get_key_down(natiny.input.KEY_LEFT) then letter_spacing = letter_spacing - dt * 12 end
line_spacing = math.max(0.4, math.min(3.0, line_spacing))
letter_spacing = math.max(-4, math.min(24, letter_spacing))
natiny.font.set_line_spacing(font, line_spacing)
natiny.font.set_letter_spacing(font, letter_spacing)
local w, h = natiny.font.measure_text(font, SAMPLE)
local lh = natiny.font.get_line_height(font)
local ascent = natiny.font.get_ascent(font)
local descent = natiny.font.get_descent(font)
natiny.render.clear(BG[1], BG[2], BG[3], 1)
natiny.render.set_color(OBJECT[1], OBJECT[2], OBJECT[3], 1)
natiny.render.rectangle_outline(X, Y, w, h, 3)
for i = 0, 1 do
local baseline = Y + ascent + i * lh
natiny.render.set_color(ACCENT[1], ACCENT[2], ACCENT[3], 0.7)
natiny.render.line(X - 30, baseline, X + w + 30, baseline, 1)
natiny.render.set_color(OBJECT[1], OBJECT[2], OBJECT[3], 0.5)
natiny.render.line(X - 20, baseline + descent, X + w + 20, baseline + descent, 1)
end
natiny.render.set_color(LIGHT_TEXT[1], LIGHT_TEXT[2], LIGHT_TEXT[3], 1)
natiny.render.text(font, X, Y, SAMPLE)
natiny.render.set_color(LIGHT_TEXT[1], LIGHT_TEXT[2], LIGHT_TEXT[3], 1)
natiny.font.set_line_spacing(font, 1.0)
natiny.font.set_letter_spacing(font, 0)
natiny.render.text(font, X, 60, string.format(
"up/down line %.2f left/right letter %.1f\nbox %.0f x %.0f",
line_spacing, letter_spacing, w, h))
end)
end)
natiny.backend.shutdown()