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


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.



[Please log in to post a comment]