evil-jrpg/nine_slice.lua

75 lines
1.6 KiB
Lua

local Object = require "lib/classic"
local NineSlice = Object:extend()
function NineSlice:new(atlas, sprites)
self.atlas = atlas
self.sprites = sprites
end
function NineSlice:draw(x, y, width, height)
local function draw(sprite, tx, ty)
local atlas = self.atlas
local sw = atlas.sw
local sh = atlas.sh
local gx = x + tx * sw
local gy = y + ty * sh
if sprite then
atlas:draw(sprite, gx, gy)
else
love.graphics.rectangle("fill", gx, gy, sw, sh)
end
end
--common variables
local right = width - 1
local bottom = height - 1
local sprites = self.sprites
if width == 1 and height == 1 then
draw(sprites.only_center, 0, 0)
elseif width == 1 then
draw(sprites.vert_top, 0, 0)
draw(sprites.vert_bottom, 0, bottom)
for cy = 1, bottom - 1 do
draw(sprites.vert_center, 0, cy)
end
elseif height == 1 then
draw(sprites.hori_left, 0, 0)
draw(sprites.hori_right, right, 0)
for cx = 1, right - 1 do
draw(sprites.hori_center, cx, 0)
end
else
--draw corners
draw(sprites.tl, 0, 0)
draw(sprites.tr, right, 0)
draw(sprites.bl, 0, bottom)
draw(sprites.br, right, bottom)
--horizontal edges
for cx = 1, right - 1 do
draw(sprites.top, cx, 0)
draw(sprites.bottom, cx, bottom)
end
--vertical edges
for cy = 1, bottom - 1 do
draw(sprites.left, 0, cy)
draw(sprites.right, right, cy)
end
--draw center
for cx = 1, right - 1 do
for cy = 1, bottom - 1 do
draw(sprites.center, cx, cy)
end
end
end
end
return NineSlice