【发布时间】:2020-10-04 01:19:48
【问题描述】:
我编写了一个函数,它使用 Freetype2 从字体创建图像。我的目标是使用字体中的所有字符创建一个 OpenGL 纹理。但首先,我想确保正确创建纹理,因此我现在将其存储为带有 stb_image_write 的图像。这是我到目前为止的进展:
如您所见,字形不是沿基线对齐,而是沿图像顶部对齐。所以我决定引入一个名为“yOffset”的变量,它描述了每个字形必须向下移动以正确对齐它们的像素数量。
根据Render FreeType text with flipped ortho, difference between top and baseline of glyph中的回答,这个偏移量可以用
yOffset = (Glyph with highest y-Bearing)->bitmap_top - glyph->bitmap_top
此值与第一个循环一起存储在“maxAscent”中,它会找出每个字形的指标。
这是字形度量的可视化表示:
这是我的功能:
static void loadFontImage(const std::string& fontPath, unsigned int fontSize, const std::string& imagePath) {
FT_Library library;
FT_Face face;
unsigned int imageWidth = 0;
unsigned int imageHeight = 0;
unsigned int maxAscent = 0;
if (FT_Init_FreeType(&library)) {
std::cerr << "Could not initialize font library" << std::endl;
std::exit(-1);
}
if (FT_New_Face(library, fontPath.c_str(), 0, &face)) {
std::cerr << "Could not load font '" << fontPath << "'" << std::endl;
std::exit(-1);
}
FT_Set_Char_Size(face, 0, fontSize * 64, 300, 300);
FT_GlyphSlot glyph = face->glyph;
for (unsigned int c = 32; c < 256; c++) {
if (c == 127) continue;
if (FT_Load_Char(face, c, FT_LOAD_RENDER)) continue;
imageWidth += glyph->bitmap.width;
if (glyph->bitmap.rows > (int)imageHeight) {
imageHeight = glyph->bitmap.rows;
}
if (glyph->bitmap_top > (int)maxAscent) {
maxAscent = glyph->bitmap_top;
}
}
unsigned int size = imageWidth * imageHeight;
unsigned char* buffer = new unsigned char[size];
unsigned int xOffset = 0;
unsigned int yOffset = 0;
for (unsigned int c = 32; c < 256; c++) {
if (c == 127) continue;
if (FT_Load_Char(face, c, FT_LOAD_RENDER)) continue;
yOffset = maxAscent - glyph->bitmap_top;
for (unsigned int x = 0; x < glyph->bitmap.width; x++) {
for (unsigned int y = 0; y < glyph->bitmap.rows; y++) {
unsigned int imageIndex = (x + xOffset) + (y + yOffset) * imageWidth;
unsigned int bitmapIndex = x + y * glyph->bitmap.width;
buffer[imageIndex] = glyph->bitmap.buffer[bitmapIndex];
}
}
xOffset += glyph->bitmap.width;
}
stbi_write_png(imagePath.c_str(), imageWidth, imageHeight, 1, buffer, imageWidth);
delete[] buffer;
}
}
但由于我引入了 yOffset,“索引超出范围”类型的异常只发生在某些字形上,因为字形的高度加上 yOffset 大于图像高度。
我认为这是因为我的“maxAscent”公式不正确,因此我的 yOffset 对于某些字符来说太大了。因此我的问题是:这确实是正确的公式,如果是,我的算法还有什么问题?是否有更简单的方法来实现正确对齐?
【问题讨论】:
标签: c++ opengl fonts text-rendering freetype2