How can I get the colour (fill) of a DisplayObject in response to an event like a touch in Corona SDK?
coronasdk
Solution
Create your rectangle:
local rectangle = display.newRect(0, 0, 100, 100)
Put your color in RGBA (you can leave out the A) format in a table, and store it as a "custom property" for the rectangle:
rectangle.fillColor = {110, 30, 25}
Through the magic of the unpack function, which returns the values of a table, pass the table to setFillColor:
rectangle:setFillColor( unpack(rectangle.fillColor) )
Now you can always get the color like so:
print( unpack(rectangle.fillColor) ) --> 110 30 25
or
print( rectangle.fillColor ) -- simply returns the table
or to put each color in a variable:
local red, green, blue, alpha = unpack(rectangle.fillColor)
You'll see how this can come in handy for other things as well.
EDIT
Just thought of another cool way of doing it, by highjacking the setFillColor function:
local function decorateRectangle(rect)
rect.cachedSetFillColor = rect.setFillColor -- store setFillColor function
function rect:setFillColor(...) -- replace it with our own function
self:cachedSetFillColor(...)
self.storedColor = {...} -- store color
end
function rect:getFillColor()
return unpack(self.storedColor)
end
end
local rectangle = display.newRect(0, 0, 100, 100)
decorateRectangle(rectangle) -- "decorates" rectangle with more awesomeness
Now you can use setFillColor to set color as normal, AND getFillColor to return it :)
rectangle:setFillColor(100, 30, 255, 255)
print(rectangle:getFillColor())
Problem
Can anyone help me find out how can I can get the color of rectangle in corona? That rectangle I already filled with color, so now I want to get that color when I touch on rectangle.