C++/SDL render text
I have a little application which uses SDL_ttf to display text. This works just fine via: TTF_RenderText_Solid( font, "text here", textColor );
However, I was wondering how I would go about rendering integers. I am assuming they would need to be casted to strings first, but I am running into a problem with this. Specifically when I want to display the x and y position of th开发者_运维问答e mouse like such:
if( event.type == SDL_MOUSEMOTION )
{
mouse_move = TTF_RenderText_Solid( font, "need mouse x and y here", textColor );
}
I believe I can grab the x and y coordinates via event.motion.x
and event.motion.y
. Is this correct?
I am assuming they would need to be casted to strings first
Nope, not casted but converted. The simplest way is using streams, something like:
#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 );
Usually I use something like boost::lexical_cast
or boost::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 );
I tend to avoid std::stringstream
unless its iterative. You have to check .good()
or the like to see if it failed, and it's not as common as you'd hope.
精彩评论