SDL在屏幕上显示分数
SDL show score on screen
正在制作《Pong》的克隆版本。在屏幕上显示分数时出现严重问题。我发现很多东西都使用图像,但我只想使用文本来显示分数。我试图使用SDL TTF库来加载字体并显示它,但它不会正确显示。我发现了这个问题如何在SDL的屏幕上blit得分?回复说使用我尝试过的SDL_BlitSurface(),我刚刚得到了一个构建错误(假设我做得正确)
下面是我调用的绘制乐谱的函数:
void Pong::drawScore(){
leftScoreChar = leftScore;
rightScoreChar = rightScore;
SDL_Color text_color = {255, 255, 255};
score = TTF_RenderText_Solid(font,
&leftScoreChar,
text_color);
score2 = TTF_RenderText_Solid(font,
&rightScoreChar,
text_color);
leftScoreText = SDL_CreateTextureFromSurface(renderer, score);
rightScoreText = SDL_CreateTextureFromSurface(renderer, score2);
SDL_RenderCopy(renderer, leftScoreText, NULL, &scoreA);
SDL_RenderCopy(renderer, rightScoreText, NULL, &scoreB);
}
当运行时输出如下:https://goo.gl/dZxDEa
对不起,我想在帖子里放一张图片,但显然我不能。
并且分数不会显示,除非存储分数的整数由于某种原因等于1并显示为零。分数肯定是在增加的因为我让游戏输出分数到主机来确保。我到底做错了什么让分数显示不正确,出现了00这样的东西?
有很多方法可以做到这一点。您可以通过SDL_Surface
或SDL_Texture
来实现。我将分别说明这两种方法。(根据需要调整)
int fontsize = 24;
int t_width = 0; // width of the loaded font-texture
int t_height = 0; // height of the loaded font-texture
SDL_Color text_color = {0,0,0};
string fontpath = "my font path";
string text = "text I want to display";
TTF_Font* font = TTF_OpenFont(fontpath.c_str(), fontsize);
SDL_Texture* ftexture = NULL; // our font-texture
// check to see that the font was loaded correctly
if (font == NULL) {
cerr << "Failed the load the font!n";
cerr << "SDL_TTF Error: " << TTF_GetError() << "n";
}
else {
// now create a surface from the font
SDL_Surface* text_surface = TTF_RenderText_Solid(font, text.c_str(), text_color);
// render the text surface
if (text_surface == NULL) {
cerr << "Failed to render text surface!n";
cerr << "SDL_TTF Error: " << TTF_GetError() << "n";
}
else {
// create a texture from the surface
ftexture = SDL_CreateTextureFromSurface(renderer, text_surface);
if (ftexture == NULL) {
cerr << "Unable to create texture from rendered text!n";
}
else {
t_width = text_surface->w; // assign the width of the texture
t_height = text_surface->h; // assign the height of the texture
// clean up after ourselves (destroy the surface)
SDL_FreeSurface(surface);
}
}
}
注意,您可以简单地停止只使用表面。然而,由于表面是软件渲染的,纹理可以说是更好的,因为它是加载在VRAM中。(点击这里阅读更多:表面和纹理的区别(SDL/general))
然后,你所要做的就是渲染它(类似于这样):
int x = 0;
int y = 0;
SDL_Rect dst = {x, y, t_width, t_height};
SDL_RenderCopy(renderer, ftexture, NULL, &dst); // renderer is a variable of the type `SDL_Renderer*`
最后,记住显示内容的顺序很重要!
相关文章:
- Winapi:屏幕截图未显示在窗口中
- 如何在快板的屏幕中显示子位图的绘制?
- SFML 中的字体.信息不显示在屏幕上.显示的不是信息,而是点
- 如何使用 openGL 在屏幕上显示加载的纹理
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 如何使用TouchGFX在LCD屏幕上显示ADC值
- 为什么屏幕上显示了一半的三角形
- 如何在屏幕上显示对象列表?
- C++列出屏幕以在第二台显示器中显示图像
- 显示和隐藏Windows 10屏幕键盘(osk.exe)时遇到问题
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- QML强制窗口将在第一个屏幕上显示
- 如何使用OpenGL在屏幕上显示三角形
- 从文本文件中读取行并显示在屏幕上
- 我的程序没有将字符显示在屏幕上
- 在屏幕上显示矢量
- 在同一屏幕上显示两个不同的对象
- 屏幕显示脚本中'.'令牌之前的预期非限定 id
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- 如果我使用的是迭代器,为什么在c++中没有屏幕显示呢