c++ /SDL渲染文本

C++/SDL render text

本文关键字:文本 SDL c++      更新时间:2023-10-16

我有一个使用SDL_ttf显示文本的小应用程序。这工作很好通过:TTF_RenderText_Solid( font, "text here", textColor );然而,我想知道我将如何去渲染整数。我假设它们首先需要被转换为字符串,但我遇到了一个问题。特别是当我想要像这样显示鼠标的x和y位置时:

if( event.type == SDL_MOUSEMOTION )
{           
    mouse_move = TTF_RenderText_Solid( font, "need mouse x and y here", textColor );
}

我相信我可以通过event.motion.xevent.motion.y获取x和y坐标。这是正确的吗?

我假设它们首先需要被强制转换为字符串

不,不是强制转换而是转换。最简单的方法是使用流,比如:

#include <sstream>
// ...
std::stringstream text;
// format
text << "mouse coords: " << event.motion.x << " " << event.motion.y;
// and display
TTF_RenderText_Solid(font, text.c_str(), textColor);
std::stringstream tmp;
tmp << "X: " << event.motion.x << " Y: " << event.motion.y;
mouse_move = TTF_RenderText_Solid( font, tmp.str().c_str(), textColor );

通常我使用boost::lexical_castboost::format

int r = 5;
std::string r_str = boost::lexical_cast<std::string>(r);
int x = 10, 7 = 4;
std::string f_str = boost::str( boost::format("Need %1% and %2% here") % x % y );

我倾向于避免std::stringstream,除非它是迭代的。您必须检查.good()或类似的检查是否失败,并且它并不像您希望的那样常见。