使用Freetype和OpenGL渲染字体

时间:2014-12-03 11:38:30

标签: opengl freetype

我有问题freetype和OpenGL。我需要在单个纹理上绘制所有加载的符号。这里' S:

    FT_Init_FreeType(&lib);
    FT_New_Face(lib, "C:\\verdana.ttf", 0, &face);
    FT_Set_Pixel_Sizes(face, 0, size);

    auto ww = 256 * size;
    auto hh = size;

    std::vector<unsigned char> buffer(ww * hh, 0);

    int off = 0;

    for (int c = 0; c < 256; c++)
    {
        FT_UInt GlyphIndex;

        GlyphIndex = FT_Get_Char_Index(face, c);

        FT_Load_Char(face, GlyphIndex, FT_LOAD_RENDER);

        FT_Bitmap bmp = face->glyph->bitmap;

        int advance = (face->glyph->advance.x >> 6);
        int bW = bmp.width; 
        int bH = bmp.rows;

        for (int h = 0; h < bH; ++h) {
            for (int w = 0; w < bW; ++w) {

                buffer[h * bW + off + w] = bmp.buffer[w + bW * h];
            }
        }

        off += advance;

    }


    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ww, hh, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &buffer[0]);

我尝试了很多方法来做到这一点。但我得到的绝对是黑色质地...... 我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

哈利路亚,我得到了解决方案!

这应该是这样的:

for (int c = 0; c < 256; c++)
    {
        FT_UInt GlyphIndex;

        GlyphIndex = FT_Get_Char_Index(face, c);

        FT_Load_Char(face, GlyphIndex, FT_LOAD_RENDER);

        FT_Bitmap bmp = face->glyph->bitmap;

        int advance = (face->glyph->advance.x >> 6);
        int bW = bmp.width; 
        int bH = bmp.rows;

        for (int h = 0; h < bH; ++h) {
            for (int w = 0; w < bW; ++w) {

                buffer[h * ww + off + w] = bmp.buffer[w + bW * h];
            }
        }

        off += advance;

    }


    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, ww, hh, 0, GL_RED, GL_UNSIGNED_BYTE, &buffer[0]);

答案 1 :(得分:0)

我认为问题在于0-255之间的某些值是不可见的或可绘制的字符,这就是为什么你什么也得不到的。

你应该检查GlyphIndex:

GlyphIndex = FT_Get_Char_Index(face, c);
if (!GlyphIndex) continue;

然后你可以期待freetype为你绘制其余的字符。