Page 1 of 1

Inconsistent values from Font:getWidth()

Posted: Tue Jan 07, 2025 11:02 am
by Altostratus
The rectangles below are drawn with the values returned from the code below and are rendered at the same position as the text:

Code: Select all

w = love.graphics.getFont():getWidth(someString)
h = love.graphics.getFont():getHeight()
,
mwq.png
mwq.png (12.69 KiB) Viewed 192 times
mwy.png
mwy.png (12.41 KiB) Viewed 192 times
mxm.png
mxm.png (9.82 KiB) Viewed 192 times
I can see no pattern or consistency here. It happens with either NotoSans-Regular.ttf or HelveticaNeueLTStd-Md.otf, so I don't believe it's font-related. It makes it impossible to properly position dynamic text, especially when trying to center it.

Is this a known bug, and is there a way around that?

Thanks.

Re: Inconsistent values from Font:getWidth()

Posted: Tue Jan 07, 2025 12:03 pm
by slime
It's likely a bug in your code (for example a different Font object is active than you thought). Can we see the code?

Re: Inconsistent values from Font:getWidth()

Posted: Tue Jan 07, 2025 12:17 pm
by Altostratus
slime wrote: Tue Jan 07, 2025 12:03 pm It's likely a bug in your code
Thanks to you, I've found it. I needed to simplify some stuff in order to make the code understandable, and by doing so I noticed I was converting the text to uppercase *after* calculating the font width. So horizontal centering now works as expected.
y.png
y.png (18.27 KiB) Viewed 164 times
However, vertical centering does not. Even though the text is converted to uppercase and so should not have any parts of the glyphs hanging below the baseline, the text is still not centered properly in the Y axis (contrary to the rectangle, which is). Here's the code:

Code: Select all

-- 'global' is just a module with some global variables

love.graphics.setLineWidth(1)
love.graphics.setColor(global.theme.circle)
love.graphics.circle('fill', 0, 0, baseRadius * 0.2)
love.graphics.setColor(global.theme.accent)
love.graphics.circle('line', 0, 0, baseRadius * 0.2)

local text = string.upper('how') -- just an example

love.graphics.setColor(global.theme.color)
love.graphics.setFont(global.font.text)
local w = love.graphics.getFont():getWidth(text)
local h = love.graphics.getFont():getHeight()
love.graphics.print(text, 0 - w/2, 0 - h/2)
love.graphics.rectangle('line', 0 - w/2, 0 - h/2, w, h)

Re: Inconsistent values from Font:getWidth()

Posted: Tue Jan 07, 2025 12:29 pm
by slime
Font:getHeight is the distance from the start of one line of text to the start of the next line, it doesn't measure baseline on its own. There's a separate method for that if you really need it.

Re: Inconsistent values from Font:getWidth()

Posted: Tue Jan 07, 2025 12:30 pm
by Altostratus
OK. Any way of otherwise getting the actual bounding box of the rendered text?