evil-jrpg/font.lua

41 lines
1008 B
Lua
Raw Normal View History

2023-04-16 21:19:45 +00:00
local Atlas = require "atlas"
2023-04-19 20:37:22 +00:00
---@class Font
2023-04-16 21:19:45 +00:00
---A set of character sprites that can be drawn as strings.
local Font = Atlas:extend()
---Creates a new font.
2023-04-21 01:19:17 +00:00
---@param image_path string The path to the source image for the atlas.
2023-04-16 21:19:45 +00:00
---@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.
2023-04-21 01:19:17 +00:00
function Font:new(image_path, sw, sh, characters)
Font.super.new(self, image_path, sw, sh)
2023-04-16 21:19:45 +00:00
---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
2023-04-21 01:19:17 +00:00
self.super.draw(self, sprite, x, y)
2023-04-16 21:19:45 +00:00
end
end
end
return Font