crankani/src/pipmeter.lua

56 lines
1.6 KiB
Lua

import "CoreLibs/graphics"
import "CoreLibs/object"
local gfx <const> = playdate.graphics
class("PipMeter").extends(gfx.sprite)
function PipMeter:init(initialValue, numPips, baseSize, sizeIncrement, spacing, circle)
PipMeter.super.init(self)
self.numPips = numPips
self.baseSize = baseSize
self.sizeIncrement = sizeIncrement or 1
self.spacing = spacing or 1
self:setZIndex(999)
-- using arithmetic progression: sum = (n * (firstValue + lastValue)) / 2
-- (plus spacing)
local padBaseSize = baseSize + spacing
local lastSize = padBaseSize + (numPips - 1) * sizeIncrement
local width = (numPips * (padBaseSize + lastSize)) / 2 - spacing
self:setSize(width, lastSize)
if circle then
self.drawFunc = gfx.drawCircleInRect
self.fillFunc = gfx.fillCircleInRect
else
self.drawFunc = gfx.drawRect
self.fillFunc = gfx.fillRect
end
self:setValue(initialValue)
end
function PipMeter:setValue(value)
local img = gfx.image.new(self:getSize())
gfx.pushContext(img)
local offset = 0
for i=1, self.numPips, 1 do
local size = self.baseSize+(self.sizeIncrement*(i-1))
if value >= i then
self.fillFunc(offset, self.height - size, size, size)
else
self.drawFunc(offset, self.height - size, size, size)
gfx.setColor(gfx.kColorWhite)
self.fillFunc(offset+1, self.height - size +1, size-2, size-2)
gfx.setColor(gfx.kColorBlack)
end
offset += size + self.spacing
end
gfx.popContext()
self:setImage(img)
end