Search code examples
stringbuttonlabelcoronasdkmeasurement

How to measure the size of the button's label in Corona SDK


I need to make a button with a dynamic width, based on its label.

So, I though in measuring the size of the label of the button but, the problem is that I cannot find nowhere how to do that without creating a display.newText of the label.

How can I do that? Is there any other way to dynamically set the button width based on its label?


Solution

  • Ok, I managed how to do that. Here's the solution:

    Button creation

    local function createButton(price)
        local button= widget.newButton{
            height = 40,
            label = price.." €",
            labelAlign = "center",
            font = "Arial",
            fontSize = 22,
            labelColor = { default = {0,0,0}, over = {255,255,255} },
            onEvent = function(event)
                if event.phase=="ended" then
                    print("done")
                end
            end
        }
        return button
    end
    

    Button position and dynamic width

    local buy=createButton("10")
    buy.width=buy._label.width
    buy._label.width=buy.width
    buy.x=700-buy.width/2
    buy.y=50
    
    local buy_2=createButton("100")
    buy_2.width=buy_2._label.width
    buy_2._label.width=buy_2.width
    buy_2.x=700-buy_2.width/2
    buy_2.y=150