Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --# Button
- -- Code 02b - Button Demo
- -- Tested for copying into Codea
- Button = class()
- function Button:init(displayName)
- -- The init function gets called before setup().
- -- This is where you define and initialize your class and
- -- its member variables. The class variables are fairly
- -- self explanatory but for completeness:
- --
- -- displayName: Is the text displayed on your button.
- -- The button will scale up and down to fit the text.
- --
- -- pos: Defines the x and y - coordinates of the button
- -- using a vector (vec2).
- --
- -- size: Is a vector which contains the width and height
- --
- -- action: Is the function that you want called when
- -- the button is tapped. Here no action is defined.
- --
- -- color: Is the color of the button fill.
- self.displayName = displayName
- self.pos = vec2(0, 0)
- self.size = vec2(0, 0)
- self.action = nil
- self.color = color(113, 66, 190, 255)
- end
- function Button:draw()
- pushStyle()
- -- pushStyle() saves the current graphic styles like stroke,
- -- width, etc. You can then do your thing and
- -- call popStyle at the end to return to this state.
- fill(self.color)
- -- fill is used initially to set the color of the button, then
- -- the font type and size is set. You could change this in
- -- your implementation of the button class if you wish.
- font("ArialRoundedMTBold")
- fontSize(22)
- -- use display name for size
- local w, h = textSize(self.displayName)
- w = w + 20
- h = h + 30
- -- As stated in the code, displayName is used to size
- -- the button and then we use the class rect to draw
- -- a rectangle
- rect(self.pos.x - w/2,
- self.pos.y - h/2,
- w, h)
- self.size = vec2(w, h)
- -- Note that class variables are designated using the
- -- self keyword. e.g. self.size. The next block of code sets
- -- the color of the button text and its position
- -- on the button.
- textMode(CENTER)
- fill(54, 65, 96, 255)
- text(self.displayName, self.pos.x, self.pos.y)
- -- Return the graphic style to what it was before you
- -- entered this function. This is considered polite
- -- behavior for a function because it can be hard to track
- -- down if the style is being changed deep within some
- -- function and you don't want it to.
- popStyle()
- end
- --# ButtonDemo
- function setup()
- print("Button Test Project")
- -- Call Button:init()
- -- pass word to be displayed on button
- -- get a Button and save to button
- button = Button("Test")
- end
- function draw()
- -- set background color
- background(40,40,50)
- -- call drawButton()
- drawButton()
- end
- function drawButton()
- -- Store button position into button.pos
- button.pos = vec2(400, HEIGHT / 2)
- -- Call draw function for button
- button:draw()
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement