This is my toggle switch class, inspired by the native Apple UI. The syntax is myToggle = Toggle("MyBoolean", x, y)
with myBoolean being a string with the name of the variable you wish to toggle. Here is my code:
--# ClipUpgrade
_clip = clip
function clip(x, y, w, h)
if x then
local m = modelMatrix()
x = x * m[1] + m[13]
y = y * m[6] + m[14]
w = w * m[1]
h = h * m[6]
_clip(x, y, w, h)
else
_clip()
end
end
--# Functions
function hit(u, v, x, y, w, h)
if u > x and v > y and u < x + w and v < y + h then
return true
end
return false
end
--# Toggle
Toggle = class()
function Toggle:init(var, x, y)
_G[var] = _G[var] or false
self.var = var
self.x = x
self.y = y
self.w = 50
self.h = 30
self.toggle = -self.w / 2
end
function Toggle:draw()
pushMatrix()
pushStyle()
translate(self.x, self.y)
strokeWidth(self.h - 4)
stroke(239, 239, 239, 255)
line(self.w / 2 + self.toggle, 0, self.w, 0)
stroke(0, 127, 239, 255)
line(0, 0, self.w / 2 + self.toggle, 0)
strokeWidth(self.h / 2 - 2)
stroke(255, 255, 255, 255)
line(self.w / 2 + self.toggle, -self.h / 4, self.w, -self.h / 4)
stroke(79, 159, 238, 255)
line(0, -self.h / 4, self.w / 2 + self.toggle, -self.h / 4)
clip(-self.h / 2 + 4, -self.h / 2, self.w + self.h - 8, self.h)
font("HelveticaNeue-Bold")
fontSize(self.h / 3 * 2)
fill(159, 159, 159, 255)
text("ON", self.toggle - self.w / 4, 0)
text("OFF",self.toggle + self.w * 1.25, 0)
clip()
noStroke()
fill(255, 255, 255, 255)
ellipse(self.w / 2 + self.toggle, 0, self.h)
fill(223, 223, 223, 255)
ellipse(self.w / 2 + self.toggle, 0, self.h - 4)
popStyle()
popMatrix()
end
function Toggle:touched(touch)
if touch.state == BEGAN
and hit(touch.x, touch.y, self.x - self.h / 2, self.y - self.h / 2 , self.w + self.h, self.h) then
self.selected = true
elseif touch.state == MOVING and self.selected then
self.toggle = math.min(self.w / 2, math.max(-self.w / 2, self.toggle + touch.deltaX))
elseif touch.state == ENDED and self.selected then
self.toggle = vec2(self.toggle, 0):normalize().x * self.w / 2
self:switch(vec2(self.toggle, 0):normalize().x)
self.selected = false
end
end
function Toggle:switch(tog)
_G[self.var] = tog == 1 and true or false
end
--# Main
function setup()
watch("bool")
bool = false
boolTog = Toggle("bool", WIDTH / 2, HEIGHT / 2)
end
function draw()
background(127, 127, 127, 255)
boolTog:draw()
end
function touched(touch)
boolTog:touched(touch)
end
P.S. This code also includes my modification to the clip function so it can work with transform and scale