2017-07-15 64 views
1

我在我的OpenGL程序中使用FreeType2库进行文本渲染。我有一个用于屏幕rgb值的缓冲区数组。对于文本渲染,我首先初始化FreeType2库,然后加载字体,设置像素大小,然后获取A char,然后获得该字形的位图,合并字形位图和我的缓冲区数组,然后使用glTexSubImage2D函数和渲染。我得到了这个结果。FreeType2多个字符和随机颜色

Render result

我对FreeType2代码:

assert(FT_Init_FreeType(&console->library) == 0); 
assert(FT_New_Face(console->library, "data/pixelize.ttf", 0, &console->face) == 0); 

assert(FT_Set_Pixel_Sizes(console->face, 0, 32) == 0); 

FT_UInt glyphIndex; 
glyphIndex = FT_Get_Char_Index(console->face, 'A'); 

assert(FT_Load_Glyph(console->face, glyphIndex, FT_LOAD_DEFAULT) == 0); 
assert(FT_Render_Glyph(console->face->glyph, FT_RENDER_MODE_NORMAL) == 0); 

FT_Bitmap bmp = console->face->glyph->bitmap; 
_tpCopyTextToConsoleBuffer(console, bmp, 10, 10); 

而且_tpCopyTextToConsoleBuffer方法是

int bitmapWidth = bmp.width; 
int bitmapHeight = bmp.rows; 

int cbx = x; // x 
int cby = y; 

for(int yy = 0; yy < bitmapHeight; yy++) { 
    for(int xx = 0; xx < bitmapWidth; xx++) { 
     int cbIndex = _tpGetIndex(console, cbx, cby); 
     int bmpIndex = (yy * bitmapWidth + xx) * 3; 

     console->buffer[cbIndex] = bmp.buffer[bmpIndex]; 
     console->buffer[cbIndex + 1] = bmp.buffer[bmpIndex + 1]; 
     console->buffer[cbIndex + 2] = bmp.buffer[bmpIndex + 2]; 

     cbx++; 
    } 
    cbx = x; 
    cby++; 
} 

_tpUpdateTexture(console); 

什么是错我的代码?

回答

3

FT_RENDER_MODE_NORMAL模式栅格化8位灰度图像。因此,如果你将其转换为RGB使用:

for(int yy = 0; yy < bmp.rows; yy++) { 
    for(int xx = 0; xx < bmp.width; xx++) { 
     uint8_t *p = console->buffer + _tpGetIndex(console, x + xx, y + yy); 
     const uint8_t *q = bmp.buffer + yy * bmp.pitch + xx; 
     p[0] = p[1] = p[2] = *q; 
    } 
} 

此外,还要避免使用assert(f() == 0)结构,因为如果你用NDEBUG开关则功能将无法在所有的被称为关闭assert秒。

+0

哇。它工作,但我不明白它是如何完成的。你能解释你是怎么做的吗? – Stradivarius

+1

您的计算使用'(yy * bmp.width + xx)* 3'作为偏移量,因为您认为'bmp'是RGB每像素3个字节并且紧密堆放在内存中的行。实际情况是'bmp'是一个灰度图像,每个像素1个字节,行之间有'bmp.pitch'个字节。因此,以上计算'yy * bmp.pitch + xx'是正确的。 – ybungalobill