Outlining text and sprites

This post was published in 2019 and is kept here for reference. It may contain information that's outdated or inaccurate.

It’s pretty simple to create an outlined text effect with a simple function, such as:

function printo(text,x,y,text_color,border_color)
  local text_color = text_color or 7
  local border_color = border_color or 0

  -- render the "outline" in each direction
  for _x=-1,1 do
    for _y=-1,1 do
      print(text,x+_x,y+_y,border_color)
    end
  end
  -- print the foreground text
  print(text,x,y,text_color)
end

-- usage:
printo("Hello world!",64,64,12,8)

The process for outlining a sprite is very similar, but it uses the pal() function to change colors and works best of all if your sprite is a single color…

-- where spr_table is like:
-- {spr_index, base_color}
function spro(spr_table,x,y,spr_color,border_color)
  local spr_color = spr_color or 7
  local border_color = border_color or 0

  -- render the "outline" in each direction
  for _x=-1,1 do
    for _y=-1,1 do
      -- replace the base_color with new border_color
      pal(spr_table[2],border_color)
      -- draw the sprite with the new color
      spr(spr_table[1],x+_x,y+_y)
    end
  end
  -- replace the base_color with the new spr_color
  pal(spr_table[2],spr_color)
  -- render the recolored sprite
  spr(spr_table[1],x,y)
  -- reset the rendering palette
  pal()
end

-- usage:
spro({1,7},64,64,12,8)

And obviously you can set this spro function up to handle more of the properties available to spr, such as number of tiles in x/y, and whether to flip or not.

As a final solution if you’re going to be doing this a lot you could combine the previous two functions to one mega outline function:

function outline(what,x,y,fc,bc)
  if typeof(what) == "string" then
    printo(what,x,y,fc,bc)
  else
    spro(what,x,y,fc,bc)
  end
end

And here’s how the final effect looks when applied to a 1-color sprite and some text, with random colors:

This post is also available in plain text

[Webmentions]

Want to reply? I've hooked up Webmentions, so give it a go!