c++ - FreeType2 多面

标签 c++ opengl freetype2

我正在使用 FreeType2 库在 OpenGL 应用程序中实现字体渲染。 我的问题是初始化多个 FT_Face 对象会使程序崩溃。我尝试使用 FT_Library 的单个实例,并为每种新字体调用 FT_Init_FreeType() 。我还尝试为每种字体提供单独的 FT_Library 实例。 两种初始化都有效,但是当我下次使用 new 运算符时,无论在哪里,我都会从 malloc.c 得到断言,实际上是在下一行代码上。

下面是初始化 FreeType2 lib 的 Font 对象创建方法:

Font::Font* create(const char* path, unsigned int size) {
  Font* font = new Font();

  FT_Init_FreeType(&(font->_ft));

  if(FT_New_Face(font->_ft, path, 0, font->_face)) {
    std::cerr << "Font: Could not load font from file " << path << "." << std::endl;
    return NULL;
  }

  FT_Set_Pixel_Sizes(*(font->_face), 0, size);
}

如果我调用一次,这种和平的代码就可以正常工作。如果我第二次调用它,然后在程序的另一部分的某个地方通过 new 创建对象,应用程序就会崩溃。

这里出了什么问题?应该有一些加载多种字体的好方法......

断言消息:malloc.c:2365: sysmalloc: 断言 (old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof) (size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' 失败。

更新:

字体类声明,每个类带有 ft 库实例的版本:

class Font
{
  public:
    static Font* create(const char* font, unsigned int size);
    void renderText(const wchar_t* text, float x, float y, float sx, float sy);

  private:
    Font();
    ~Font();

    FT_Library _ft;
    FT_Face* _face;
};

renderText() 方法基本上使用 _face 来查看所需的字符并渲染它们。

最佳答案

在调用FT_New_Face之前,您确定font->_face是新的吗?因此,如果 font->_face 为 NULL,则需要新的 FT_Face

注意:没有必要为每个 Font 实例初始化一个FT_Library。您可以将 Font::_ft 设为静态。

最后,代码应该是:

class Font
{
public:
    static FT_Library      _ft;
    static Font* create(const char* path, unsigned int size)
    {
        Font* font = new Font();

        if (Font::_ft == NULL)
            if (FT_Init_FreeType(&Font::_ft))
                return NULL;

        if (font->_face == NULL)
            font->_face = new FT_Face;
        if (FT_New_Face(font->_ft, path, 0, font->_face)) {
            std::cerr << "Font: Could not load font from file " << path << "." << std::endl;
            return NULL;
        }

        FT_Set_Pixel_Sizes(*(font->_face), 0, size);
        return font;
    }

private:
    // Set the member - _face to NULL when call constructor
    Font() : _face(NULL) {}
    ~Font() { /* release the memory */ }
    FT_Face*        _face;
};

// Set the static member - _ft to NULL
FT_Library Font::_ft = NULL;

最后,在调用析构函数时,您需要取消初始化/释放有关 FreeType2 的所有内存。

注意:FT_New_Face的第四个变量(FT_Face)必须是实例。 FT_New_Face 不为 FT_Face 分配内存。

关于c++ - FreeType2 多面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21517421/

相关文章:

c++ - "main"循环的聊天服务器设计

c++ - 尽管有 vao,glVertexAttribPointer 仍导致无效操作错误

java - 浏览器渲染和流式传输

opengl - 为什么我们必须分别指定曲面分割着色器的输入和输出补丁大小?

c++ - 如何使用 Freetype 沿基线对齐字形?

c++ - 硬件加速 Unicode 文本渲染

c# - 如何将 VC++ 2015 可再发行组件与我的 ClickOnce (.NET) 应用程序捆绑在一起?

c++ - 数据类型匹配,但我的链接列表仍然出错?

c++ - 初始化不工作

c++ - 如何将 freetype2.6 库添加到 code::blocks