memononen / nanovg

Antialiased 2D vector drawing library on top of OpenGL for UI and visualizations.
zlib License
5.06k stars 767 forks source link

nvgTextBounds doesn't calculate for spaces at the end of a string #636

Closed senxd closed 2 years ago

senxd commented 2 years ago

Given text such as "abc ", nvgTextBounds doesn't include the space at the end. I assume this is an intentional feature. Is there any other way to get the bounds of the text including space besides appending another space if there is one at the end?

mulle-nat commented 2 years ago

Looking at the source, the calculation for the spacing is done by fons__tt_getGlyphKernAdvance:

int fons__tt_getGlyphKernAdvance(FONSttFontImpl *font, int glyph1, int glyph2)
{
    FT_Vector ftKerning;
    FT_Get_Kerning(font->font, glyph1, glyph2, FT_KERNING_DEFAULT, &ftKerning);
    return (int)((ftKerning.x + 32) >> 6);  // Round up and convert to integer
}

So the answer should lie with FreeType (or stb_truetype) I believe.

senxd commented 2 years ago

Ah. I see. I just made a simple workaround by appending a space if needed. Thanks!

mulle-nat commented 1 year ago

I revise my answer here. Actually I think nvgTextBounds is buggy. There is a difference how the text bounds are calculated and how the actual drawing is then performed.This shows up most noticeably with the surrounding spaces. The way to get the proper width is to use nvgTextGlyphPositions and accumulate the glyphs width.

In this picture you can see how in the third line " Space around ", you can see the actually emitted spaces and notice how the blue enclosing rectangle (uses nvgTextGlyphPositions) is perfect:

image

You can also see that there is still a problem with the right alignment in my code :smile:

zeroxer commented 11 months ago

Any method to fix the space render error?

mulle-nat commented 11 months ago

I use nvgTextGlyphPositions instead of nvgTextBounds, or what do you mean ?