SDL游戏编程(3)使用SDL扩展类库显示PNG图片和字体

SDL游戏编程(3)使用SDL扩展类库显示PNG图片和字体
SDL本身只支持加载BMP文件,如果你想显示其他类型的图像文件,就要用到扩展类库,扩展类库里面还有其他一些组件,你可以在这里下载到 http://www.libsdl.org/projects/SDL_image/
下载完以后,按照教程一配置,我们就可以显示一张PNG图片了。
以下是具体的代码,与教程二很相似,如有疑问请参考教程二。
#include 
" SDL.h "
#include 
< SDL_image.h >
#include 
< string >
SDL_Surface 
* screen;
SDL_Surface 
* background;
SDL_Surface 
* load_image( std:: string  filename ) 
{
    
// The image that's loaded
    SDL_Surface *  loadedImage  =  NULL;

    
// The optimized image that will be used
    SDL_Surface *  optimizedImage  =  NULL;

    
// Load the image using SDL_image
    loadedImage  =  IMG_Load( filename.c_str() );

    
// If the image loaded
     if ( loadedImage  !=  NULL )
    
{
        
// Create an optimized image
        optimizedImage  =  SDL_DisplayFormat( loadedImage );

        
// Free the old image
        SDL_FreeSurface( loadedImage );
    }


    
// Return the optimized image
     return  optimizedImage;
}

void  apply_surface( int  x, int  y,SDL_Surface  * source ,SDL_Surface  * destinaion)
{
    SDL_Rect rect;
    rect.x
= x;
    rect.y
= y;
    SDL_BlitSurface(source,NULL,destinaion,
& rect);

}

int  main(  int  argc,  char *  args[] )
{
    
// Start SDL
    SDL_Init( SDL_INIT_EVERYTHING );

    
// Quit SDL
    screen = SDL_SetVideoMode( 640 , 480 , 32 ,SDL_SWSURFACE);
    background
= load_image( " Dockxrt5.jpg " );

    apply_surface(
0 , 0 ,background,screen);

    
if (SDL_Flip(screen) ==- 1 )
        
return   - 1 ;
    SDL_FreeSurface(background);
    SDL_Delay(
2000 );
    SDL_FreeSurface(background);
    SDL_Quit();

    
return   0 ;    
}

以下代码用SDL_TTF扩展类库加载一个TTF字体文件,并用该字体显示一段文字。
 1 #include  " SDL.h "
 2 #include  < SDL_ttf.h >
 3 #include  < string >
 4 SDL_Surface  * screen;
 5 SDL_Surface  * background;
 6 void  apply_surface( int  x, int  y,SDL_Surface  * source ,SDL_Surface  * destinaion)
 7 {
 8     SDL_Rect rect;
 9     rect.x = x;
10     rect.y = y;
11     SDL_BlitSurface(source,NULL,destinaion, & rect);
12
13 }

14 int  main(  int  argc,  char *  args[] )
15 {
16      // Start SDL
17
18     SDL_Init( SDL_INIT_EVERYTHING );
19      if (TTF_Init() ==- 1 )
20          return   - 1 ;
21     TTF_Font  * font = NULL;
22     font = TTF_OpenFont( " verdana.ttf " , 14 );
23      if (font  ==  NULL)
24          return   - 1 ;
25
26      // Quit SDL
27     SDL_Color textColor = { 255 , 255 , 255 } ;
28     SDL_Color textBgColor = { 0 , 0 , 0 ,} ;
29     screen = SDL_SetVideoMode( 640 , 480 , 32 ,SDL_SWSURFACE);
30     background = TTF_RenderText_Blended( font,  " why it can not display chinese " , textColor);
31
32     apply_surface( 0 , 0 ,background,screen);
33
34      if (SDL_Flip(screen) ==- 1 )
35          return   - 1 ;
36
37     SDL_Delay( 100000 );
38     SDL_Quit();
39
40      return   0 ;    
41 }

42

你可能感兴趣的:(SDL游戏编程(3)使用SDL扩展类库显示PNG图片和字体)