【问题标题】:How can I get the full text at SDL? (Not console)如何在 SDL 获得全文? (不是控制台)
【发布时间】:2022-01-14 17:16:17
【问题描述】:

我正在使用 C++ 为游戏创建菜单,但在读取文本文件 (.cfg) 时出现问题,我想将其显示到屏幕上(使用 SDL,而不是控制台)。

问题是在 SDL 中,我只得到最后一行。这是为什么呢?

这是我的代码:

fstream characters;
characters.open("characters.cfg", ios::in);
while (getline(characters, line))
cout << line << endl;

我创建了一个字符串来用 SDL_ttf 显示它:

void renderUI() {
SDL_Surface* textSurface;
SDL_Texture* textTexture;
SDL_Rect textRect;

SDL_Color white = { 255,255,255 };

textRect.w = 250;
textRect.h = 20;
textRect.x = 150;
textRect.y = 200;

string names = line;

textSurface = TTF_RenderText_Blended(gameFont, names.c_str(), white);
textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);

if (textSurface == NULL)
{
    cout << "TTF_RenderText_Solid() Failed: " << TTF_GetError() << endl;
    TTF_Quit();
    SDL_Quit();
    exit(1);
}


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

这里有一张照片显示我在控制台中获得了全文,但在 SDL 中没有:

示例照片:

【问题讨论】:

  • 不应该移动矩形以防止覆盖之前写入的内容吗?
  • 看起来line 本身在getline 循环中不断被覆盖。当renderUI 有机会画出任何东西时,Highlander's Law 已经开始了,Shang Tsung 是最后一根绳子。
  • 您可能希望将这些行存储在 std::vector 或类似名称中。但要小心。 lines 具有全局变量的恶臭,可以在 getline 循环加载它或 renderUI 读取它时更改。不要对vector 犯同样的错误。

标签: c++ sdl iostream sdl-ttf


【解决方案1】:

我有办法。代码如下:

fstream characters;
string line;
string text;

characters.open("characters.cfg", ios::in);
while (getline(characters, line))
{
    text = text + line + "\n";
}
characters.close();

这里是 SDL_ttf 的代码和 SDL 换行问题的解决方案:

    SDL_Surface* textSurface;
    SDL_Texture* textTexture;
    SDL_Rect textRect;
    SDL_Color white = { 255,255,255 };
    
    textRect.w = 250;
    textRect.h = 400;
    textRect.x = 150;
    textRect.y = 185;
   
    textSurface = TTF_RenderText_Blended_Wrapped(gameFont, text.c_str(), white, 500); 
    textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);

    // If TTF_RenderText_Solid() Fail

    if (textSurface == NULL)
    {
        cout << "TTF_RenderText_Solid() Failed: " << TTF_GetError() << endl;
        TTF_Quit();
        SDL_Quit();
        exit(1);
    }

将此用于 SDL_TTF 的换行问题:

TTF_RenderText_Blended_Wrapped for be able to use line break

【讨论】:

  • 你能解释一下什么有效吗?为什么?也许指出您的答案中的代码与您的问题中的代码之间的相关差异。
  • 当然,问题是,使用此代码,您可以使用换行符读取文本文件中的所有行:“text = text + line + "\n";" .并且使用此函数 "TTF_RenderText_Blended_Wrapped" SDL_TTF 允许能够读取换行符 "\n" ,它需要额外的参数:以像素为单位的宽度,之后文本将进入下一行(宽度是数字 500 在末尾代码)。
猜你喜欢
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2023-03-17
  • 1970-01-01
  • 2019-04-04
相关资源
最近更新 更多