SDL2 渲染文本问题

SDL2 rendering text issues

我有一个菜单,其中有很多正在呈现的文本可以在 size/color/position 中更改,所以我在我的菜单中创建了两个功能 class...:[=​​12=]

void drawText(string text,int text_size,int x,int y, Uint8 r,Uint8 g,Uint8 b);
void updateTexts();

updateTexts() 函数位于游戏循环中并包含许多 drawText 函数,当我启动程序时,我注意到程序内存从 4mb 逐渐增加到大约 1gb(它应该保持在 4mb)然后它崩溃了。我认为问题存在是因为 TTF_OpenFont" 一直是 运行,尽管我需要一种方法能够在我的菜单根据用户输入更改时动态创建新的字体大小。

有更好的方法吗?

两个函数的代码:

void Menu::drawText(string text,int text_size,int x,int y, Uint8 r,Uint8 g,Uint8 b)
{
    TTF_Font* arial = TTF_OpenFont("arial.ttf",text_size);
    if(arial == NULL)
    {
        printf("TTF_OpenFont: %s\n",TTF_GetError());
    }
    SDL_Color textColor = {r,g,b};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(arial,text.c_str(),textColor);
    if(surfaceMessage == NULL)
    {
        printf("Unable to render text surface: %s\n",TTF_GetError());
    }
    SDL_Texture* message = SDL_CreateTextureFromSurface(renderer,surfaceMessage);
    SDL_FreeSurface(surfaceMessage);
    int text_width = surfaceMessage->w;
    int text_height = surfaceMessage->h;
    SDL_Rect textRect{x,y,text_width,text_height};

    SDL_RenderCopy(renderer,message,NULL,&textRect);
}

void Menu::updateTexts()
{
    drawText("Item menu selection",50,330,16,0,0,0);
    drawText("click a menu item:",15,232,82,0,0,0);
    drawText("item one",15,59,123,0,0,0);
    drawText("item two",15,249,123,0,0,0);
    drawText("item three",15,439,123,0,0,0);
    drawText("item four",15,629,123,0,0,0);
}

每个打开的字体、创建的表面和创建的纹理都使用内存。

如果您需要的不同资源的收集是有限的,例如只有 3 个不同 text_size,最好创建一次,然后重复使用。 例如通过将它们存储在某种缓存中:

std::map<int, TTF_Font*> fonts_cache_;

TTF_Font * Menu::get_font(int text_size) const
{
  if (fonts_cache_.find(text_size) != fonts_cache_.end())
  {
    // Font not yet opened. Open and store it.
    fonts_cache_[text_size] = TTF_OpenFont("arial.ttf",text_size);
    // TODO: error checking...
  }

  return fonts_cache_[text_size];
}

void Menu::drawText(string text,int text_size,int x,int y, Uint8 r,Uint8 g,Uint8 b)
{
  TTF_Font* arial = get_font(text_size)
  ...
}

Menu::~Menu()
{
  // Release memory used by fonts
  for (auto pair : fonts_cache_)
    TTF_CloseFont(pair.second);
  ...
}

对于应在每次方法调用时分配的动态资源,您不应忘记释放它们。目前您没有释放 TTF_Font* arialSDL_Texture* message 的内存;做:

void Menu::drawText(string text,int text_size,int x,int y, Uint8 r,Uint8 g,Uint8 b)
{
  ...
  TTF_CloseFont(arial);
  SDL_DestroyTexture(message);
}