[英]How to get text width in FreeType?
I inherited a code where author prints some text (not necessarily in monospace font) using FreeType and OpenGL. 我继承了一个代码,其中作者使用FreeType和OpenGL打印了一些文本(不一定是等宽字体)。
I need to calculate printed text width so I can align it properly. 我需要计算打印的文本宽度,以便正确对齐。
Here is the code he wrote: 这是他写的代码:
freetype::font_data font;
font.init(fontPath.c_str(), fontSize);
freetype::print(font, x, y, "%s", str.c_str());
Here is the FreeType source with print
function. 这是带有
print
功能的FreeType源。
I couldn't think of any way to get the text width by modifying print
function and I tried editing font's init
function (also in mentioned file) to return face->glyph->metrics.width
but there was an exception saying that face->glyph
is null. 我想不出任何办法通过修改来获取文本的宽度
print
功能,我试图编辑字体的init
函数(也提到文件)返回face->glyph->metrics.width
但有一个例外,说face->glyph
为空。 But I don't think I should even be trying to edit sources of libraries. 但我认为我什至不应该尝试编辑库源。
Since I have no clue how to get the text width I'm considering somehow printing the text, getting the width of what was printed and printing something over it. 由于我不知道如何获取文本宽度,因此我正在考虑以某种方式打印文本,获取已打印内容的宽度并在其上进行打印。 Any ideas on that maybe?
有什么想法吗?
if you are confined to using Latin characters, here is a simple and dirty way to do it. 如果您仅限使用拉丁字符,这是一种简单而肮脏的方法。
you can iterate over glyphs, load each glyph and then calculate the bounding box: 您可以遍历字形,加载每个字形,然后计算边界框:
int xmx, xmn, ymx, ymn;
xmn = ymn = INT_MAX;
xmx = ymx = INT_MIN;
FT_GlyphSlot slot = face->glyph; /* a small shortcut */
int pen_x, pen_y, n;
... initialize library ...
... create face object ...
... set character size ...
pen_x = x;
pen_y = y;
for ( n = 0; n < num_chars; n++ )
{
FT_UInt glyph_index;
/* retrieve glyph index from character code */
glyph_index = FT_Get_Char_Index( face, text[n] );
/* load glyph image into the slot (erase previous one) */
error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
if ( error )
continue; /* ignore errors */
/* convert to an anti-aliased bitmap */
error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );
if ( error )
continue;
/* now, draw to our target surface */
my_draw_bitmap( &slot->bitmap,
pen_x + slot->bitmap_left,
pen_y - slot->bitmap_top );
if (pen_x < xmn) xmn = pen_x;
if (pen_y < ymn) ymn = pen_y;
/* increment pen position */
pen_x += slot->advance.x >> 6;
pen_y += slot->advance.y >> 6; /* not useful for now */
if (pen_x > xmx) xmx = pen_x;
if (pen_y > ymx) ymx = pen_y;
}
but if you want to do it more professionally, I think you must use harfbuzz (or a complex text shaping library). 但是,如果您想更专业地做,我认为您必须使用harfbuzz(或复杂的文本整形库)。 it is a one-size-fits-all soultion, meaning once you get it compiled, you can use it to draw and measure not only Latin strings but also Unicode ones.
它是千篇一律的灵魂,这意味着一旦编译完成,就可以使用它不仅绘制和测量拉丁字符串,而且还可以绘制和测量Unicode字符串。 I strongly recommend you use this one.
我强烈建议您使用这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.