2010-08-30 30 views
-1

我試圖在SDL窗口中使用TTF呈現文本時遇到了很多麻煩。我對C++有一點新意,並希望以一種「新手」的方式解釋這一點。 (如果可能,用一些示例代碼?)SDL + SDL_TTF:如何在SDL + SDL_TTF中呈現文本? (C++)

謝謝!

+0

那你試試?你有什麼(代碼方面)?什麼沒有用? – genpfault 2010-08-31 00:45:59

+0

地獄我甚至不理解我自己的代碼了。但非常多: SDL_Color fontcolor = {fgR,fgG,fgB,fgA}; SDL_Color fontbgcolor = {bgR,bgG,bgB,bgA}; SDL_Surface * text; if(quality == solid)referenced_text = TTF_RenderText_Solid(fonttodraw,text,fontcolor); else if(quality == shaded)results_text = TTF_RenderText_Shaded(fonttodraw,text,fontcolor,fontbgcolor); else if(quality == blended)results_text = TTF_RenderText_Blended(fonttodraw,text,fontcolor); return text; – Lemmons 2010-09-01 02:52:05

+0

看一看http://lazyfoo.net/SDL_tutorials/lesson07/index.php – Adam 2010-09-01 03:34:10

回答

2

這是一個簡單的例子。確保你的目錄中有arial.ttf或你選擇的truetype字體。您需要鏈接-lSDL -lSDL_ttf。

#include "SDL.h" 
#include "SDL_ttf.h" 

SDL_Surface* screen; 
SDL_Surface* fontSurface; 
SDL_Color fColor; 
SDL_Rect fontRect; 

SDL_Event Event; 

TTF_Font* font; 

//Initialize the font, set to white 
void fontInit(){ 
     TTF_Init(); 
     font = TTF_OpenFont("arial.ttf", 12); 
     fColor.r = 255; 
     fColor.g = 255; 
     fColor.b = 255; 
} 

//Print the designated string at the specified coordinates 
void printF(char *c, int x, int y){ 
     fontSurface = TTF_RenderText_Solid(font, c, fColor); 
     fontRect.x = x; 
     fontRect.y = y; 
     SDL_BlitSurface(fontSurface, NULL, screen, &fontRect); 
     SDL_Flip(screen); 
} 

int main(int argc, char** argv) 
{ 
    // Initialize the SDL library with the Video subsystem 
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE); 

    //Create the screen 
    screen = SDL_SetVideoMode(320, 480, 0, SDL_SWSURFACE); 

    //Initialize fonts 
    fontInit(); 

    //Print to center of screen 
    printF("Hello World", screen->w/2 - 11*3, screen->h/2); 

    do { 
     // Process the events 
     while (SDL_PollEvent(&Event)) { 
      switch (Event.type) { 

       case SDL_KEYDOWN: 
        switch (Event.key.keysym.sym) { 
        // Escape forces us to quit the app 
         case SDLK_ESCAPE: 
          Event.type = SDL_QUIT; 
         break; 

         default: 
         break; 
        } 
       break; 

      default: 
      break; 
     } 
    } 
    SDL_Delay(10); 
    } while (Event.type != SDL_QUIT); 

    // Cleanup 
    SDL_Quit(); 

    return 0; 
}