I’ve been writing lots of code lately and I find that I keep having to type out
myobject.anchorX, myobject.anchorY = number, number
So I checked the Corona docs to see if there if there was a convenience function for this but didn’t see anything. I decided to create my own and wrote the code below. Theoretically, it should work with all display objects and widgets that support the use of anchor points.
Just slap this code in your main.lua or put it in a file that gets required in main.lua and you should be good to go. To use it, simply create your display object like normal, and then call
myobject:setAnchor( numberX, numberY )
and the anchorX and anchorY will be set accordingly. Enjoy!
UPDATE: Added functions to grab and release touch focus in touch event handlers.
local widget = require("widget") local libraries = {display, widget} for i, library in pairs(libraries) do for k,v in pairs(library) do if(type(library[k]) == "function" and k:sub(1,3) == "new") then local oldFunction = library[k] library[k] = function(...) local displayObject = oldFunction(...) --Takes either one integer (1-9) as shorthand or two numbers function displayObject:setAnchor(...) assert(..., "Bad call to setAnchor: number expected, got nil") local args = {...} local referencePoints = {{0,0}, {.5,0}, {1,0}, {0,.5}, {.5,.5}, {1,.5}, {0,1}, {.5,1}, {1,1}} local anchorX, anchorY = unpack( #args \> 1 and args or referencePoints[args[1]] ) self.anchorX, self.anchorY = anchorX, anchorY end function displayObject:grabFocus() display.getCurrentStage():setFocus( self ) self.isFocus = true end function displayObject:releaseFocus() display.getCurrentStage():setFocus( nil ) self.isFocus = nil end return displayObject end end end end
P.S. Use at your own risk! I don’t know how future updates to Corona will affect this code. Also I have not extensively tested it with every display object that Corona can create.