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.


    
main.lua
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("common/fonts/roboto.ttf"), 34)

local SAMPLE = "Typography\nText layout"
local BG = natiny.color.from_hex("#151E2C")
local OBJECT = natiny.color.from_hex("#A9B3C5")
local LIGHT_TEXT = natiny.color.from_hex("#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)

        natiny.render.set_color(OBJECT)
        natiny.render.rectangle_outline(X, Y, w, h, 3)

        for i = 0, 1 do
            local baseline = Y + ascent + i * lh
            natiny.render.set_color(natiny.color.from_hex("#F8F9FDB3"))
            natiny.render.line(X - 30, baseline, X + w + 30, baseline, 1)
            natiny.render.set_color(natiny.color.from_hex("#A9B3C580"))
            natiny.render.line(X - 20, baseline + descent, X + w + 20, baseline + descent, 1)
        end

        natiny.render.set_color(LIGHT_TEXT)
        natiny.render.text(font, X, Y, SAMPLE)

        natiny.render.set_color(LIGHT_TEXT)
        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()