Skip to content

Instantly share code, notes, and snippets.

@biomood
Created June 10, 2011 19:04
Show Gist options
  • Save biomood/1019538 to your computer and use it in GitHub Desktop.
Save biomood/1019538 to your computer and use it in GitHub Desktop.
Code for nLove that displays user-created fonts correctly
require "string"
---------------------------------------------------------
-- a font library for the dingoo --
-- allows for multiple fonts --
---------------------------------------------------------
-- creates a table of images from a font
-- ImageData source, String char_list, Number char_width, Number seperator_width
local function setFontImage(source, char_list, char_width, seperator_width)
local font = {}
font.char_width = char_width
font.char_height = source:getHeight()
font.seperator_width = seperator_width
-- iterate through string and get correct image for each character
for i=1, char_list:len() do
-- get the single substr at i
local char = char_list:sub(i, i)
-- create new imagedata for char
local char_data = love.image.newImageData(font.char_width, font.char_height)
-- copy the section of the char image we want for this character
local j = i -1
local src_x = (j*char_width) + (i*seperator_width)
char_data:paste(source, 0, 0, src_x, 0, font.char_height)
font[char] = love.graphics.newImage(char_data)
end
return font
end
-- print the text at the selected x,y
-- returns true if displayed, false if not
local function dingPrint(font, text, x, y)
-- iterate through each char and print
for i=1, text:len() do
local j = i -1
-- set correct position
local xpos = x + (j*font.char_width) + (j*font.seperator_width)
-- get the correct character to display
local char = text:sub(i, i)
-- check if the char is in the table
if (font[char] ~= nil) then
love.graphics.draw(font[char], xpos, y, 0, 1, 1, 0, 0)
else
return false
end
end
return true
end
-- package
dingoo_font = {
setFontImage = setFontImage,
dingPrint = dingPrint,
}
-- create an imagedata from the font image
font_data = love.image.newImageData("font.png")
-- pass in the font imagedata
-- a string that represents each character in the font image
-- the width of each character in the font image
-- width of the separator blocks between each character in the font image
-- returns table containing font details
font = dingoo_font.setFontImage(font_data, " ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!?[]", 12, 4)
-- display the 'Hello World' text using our own font
-- at x 123, and y 171 using the font created above
dingoo_font.dingPrint(font, 'Hello World', 123, 171)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment