簡體   English   中英

SDL2渲染文本問題

[英]SDL2 rendering text issues

我有一個菜單,其中渲染了很多可以改變大小/顏色/位置的文本,因此我在菜單類中做了兩個功能...:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM