A test with a canvas.
Code: Select all
;Include Switch Button
EnableExplicit
;-Private procedure
Procedure DrawSwitchButton(Gadget, x, y, width, height)
Protected Setup.s, State, onRGBColor, offRGBColor, SwitchX, BodyColor
If IsGadget(Gadget)
Setup = Str(GetGadgetData(Gadget))
State = Val(Mid(Setup, 1, 1)) - 1
onRGBColor = Val(Mid(Setup, 2, 8))
offRGBColor = Val(Mid(Setup, 10, 8))
If State = #True
SwitchX = 1
BodyColor = onRGBColor
Else
SwitchX = width - height
BodyColor = offRGBColor
EndIf
;Draw switch button
StartDrawing(CanvasOutput(gadget))
;body
RoundBox(0, 0, width-1, height-1, 6, 6, BodyColor)
DrawingMode(#PB_2DDrawing_Outlined)
RoundBox(0, 0, width-1, height-1, 6, 6, RGB(105, 105, 105))
;Switch
DrawingMode(#PB_2DDrawing_Default)
RoundBox(SwitchX, 1, height-2, height-3, 6, 6, RGB(220, 220, 220))
DrawingMode(#PB_2DDrawing_Outlined)
RoundBox(SwitchX, 1, height-2, height-3, 6, 6, RGB(105, 105, 105))
StopDrawing()
EndIf
EndProcedure
;-Public procedures
;Draw canvas (option #PB_Canvas_Transparent)
Procedure SwitchButton(Gadget, x, y, width, height, onRGBColor = $00FF00, offRGBColor = $D3D3D3)
Protected Setup.s = "1" + RSet(Str(onRGBColor), 8, "0") + RSet(Str(offRGBColor), 8, "0")
;Format Setup
;01-01 State (0 or 1) + 1
;02-09 On RGB Color
;10-17 Off RGB Color
CanvasGadget(Gadget, x, y, width, height, #PB_Canvas_Transparent)
SetGadgetData(Gadget, Val(Setup))
DrawSwitchButton(Gadget, GadgetX(Gadget), GadgetY(Gadget), GadgetWidth(Gadget), GadgetHeight(Gadget))
EndProcedure
;Returns the state of the gadget (1 = On, 0 = off)
Procedure GetSwitchButton(Gadget)
If IsGadget(Gadget)
ProcedureReturn Val(Mid(Str(GetGadgetData(Gadget)), 1, 1)) - 1
EndIf
EndProcedure
;Set the actual state (1 = On, 0 = off)
Procedure SetSwitchButton(Gadget, State)
Protected Setup.s
If IsGadget(Gadget)
Setup = Str(GetGadgetData(Gadget))
Setup = Str(State + 1) + Mid(Setup, 2, 16)
SetGadgetData(Gadget, Val(Setup))
DrawSwitchButton(Gadget, GadgetX(Gadget), GadgetY(Gadget), GadgetWidth(Gadget), GadgetHeight(Gadget))
EndIf
EndProcedure
;-
;-Zone Test
Declare onClick()
OpenWindow(0, 0, 0, 0, 0, "", #PB_Window_Background)
;Two SwitchButtons
SwitchButton(1, 20, 20, 50, 25)
SetSwitchButton(1, #True)
SwitchButton(2, 20, 50, 50, 25, RGB(0, 255, 0), RGB(0, 0, 255))
BindGadgetEvent(1, @onClick(), #PB_EventType_LeftClick)
BindGadgetEvent(2, @onClick(), #PB_EventType_LeftClick)
Procedure onClick()
Protected Gadget = EventGadget()
If GetSwitchButton(Gadget) = #False
SetSwitchButton(Gadget, #True)
Else
SetSwitchButton(Gadget, #False)
EndIf
Debug "Gadget : " + Gadget + " State : " + GetSwitchButton(Gadget)
EndProcedure