Log In  

I just submitted this to the Wiki, but figured it might be more visible here.

Here is how I handled text centering in some recent code. Any improvements are welcome.

textlabel="this is some cool text!!!"

function hcenter(s)
    -- string length times the 
    -- pixels in a char's width
    -- cut in half and rounded down
    return 64-flr((#s*4)/2)
end

function vcenter(s)
    -- string char's height
    -- cut in half and rounded down
    return 64-flr(5/2)
end

function _draw()
    rectfill(0,0,128,128,0)
    print(textlabel,hcenter(textlabel),vcenter(textlabel),8)
end
P#21924 2016-05-31 14:50 ( Edited 2016-05-31 22:42)

Here is the function I'm using:

function print_center(s,y,c) print(s,64-(#s*2),y,c) end

For horizontal centering, (#s4)/2 will always be the same as (#s2), which simplifies things a bit.

As for vertical centering, if it is only one line, that will always be 62 :) I usually just want to center a line horizontally at a given Y coordinate.

P#21968 2016-05-31 18:42 ( Edited 2016-05-31 22:42)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-29 07:37:19 | 0.005s | Q:11