2015-07-12 112 views
2

在乒乓克隆上工作。尝试在屏幕上显示分数时遇到严重问题。我发现的很多东西都在使用图像,但我只是想用文本来显示分数。我正在尝试使用SDL TTF库加载字体并显示它,但无法正确显示。我发现这个问题How to blit Score on screen in SDL?和答复说要用SDL_BlitSurface(),我试过,我刚刚得到一个编译错误(假设我是做正确)SDL在屏幕上显示得分

这是我呼吁绘制得分函数:

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

Aplogies,我会把图像中的职位,但显​​然我不能。

除非存储分数的整数出于某种原因等于1并且显示零,否则分数将不会显示。因为我有游戏输出到控制台的分数以确保分数是绝对增加。那么,我做错了什么,使我的分数显示不正确,并有一些00的东西?

回答

0

有很多方法可以做到这一点。 您可以通过SDL_SurfaceSDL_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中可能会更好。 (在这里阅读更多:Difference between surface and texture (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*` 

最后,请记住,在如何显示的东西的顺序很重要!

+0

我试着复制并粘贴这段代码,并将其调整为我的程序,但现在我没有从窗口上的任何类型的文本输出时得到任何输出。 – CharlieFan39

+0

@ CharlieFan39您是否正确初始化相应的库?您是否启用了“SDL_RENDERER_ACCELERATED”? – jrd1

+0

是的,我有。我之前尝试的方式给了我不正确的输出,但由于某种原因,我现在没有任何输出。我很迷惘。 – CharlieFan39