evil-jrpg/font.lua

41 lines
1008 B
Lua

local Atlas = require "atlas"
---@class Font
---A set of character sprites that can be drawn as strings.
local Font = Atlas:extend()
---Creates a new font.
---@param image_path string The path to the source image for the atlas.
---@param sw integer The width of each sprite.
---@param sh integer The height of each sprite.
---@param characters string[] A list of characters with indices corresponding to each sprite.
function Font:new(image_path, sw, sh, characters)
Font.super.new(self, image_path, sw, sh)
---A map of characters to sprites.
self.characters = {}
for sprite, ch in ipairs(characters) do
if ch then
self.characters[ch] = sprite
end
end
end
---Draws a string with this font.
function Font:draw(text, x, y)
local x = x or 0
local y = y or 0
for i = 1, #text do
local c = text:sub(i, i)
local sprite = self.characters[c]
if sprite then
local x = (i - 1) * self.sw + x
self.super.draw(self, sprite, x, y)
end
end
end
return Font