在前面已经学习了各种图片格式的装载方式和如何抠色,现在可以来看看文字怎么加载了,首先要在http://www.libsdl.org/projects/SDL_ttf/下载相关的装载ttf的插件,因为SDL不能显式支持ttf文件,用这个插件你可以从真体字生成表面。
代码:
//The headers #include "SDL.h"
#include <string>
//设置屏幕属性 const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const int SCREEN_BPP = 32;
//定义属性SDL_Surface *background = NULL; SDL_Surface *message = NULL; SDL_Surface *screen = NULL;
//事件结构 SDL_Event event;
//后面将要被用到的字体TTF_Font *font = NULL;
//字体颜色 SDL_Color textColor = { 0, 255, 255 };
SDL_Surface *load_image( std::string filename ) { SDL_Surface* loadedImage = NULL; SDL_Surface* optimizedImage = NULL; loadedImage = IMG_Load( filename.c_str() ); if( loadedImage != NULL ) { optimizedImage = SDL_DisplayFormat( loadedImage ); SDL_FreeSurface( loadedImage ); if( optimizedImage != NULL ) { SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ) ); } } return optimizedImage; }
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL ) { SDL_Rect offset; offset.x = x; offset.y = y; SDL_BlitSurface( source, clip, destination, &offset ); }
bool init() { //初始化所有子系统 if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) { return false; } screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE ); if( screen == NULL ) { return false; } //初始化字体,在使用字体信息之前一定要TTF_Init来初始化字体信息 if( TTF_Init() == -1 ) { return false; } SDL_WM_SetCaption( "TTF Test", NULL ); return true; }
bool load_files() { background = load_image( "D:/Users/lucy/Documents/Visual Studio 2008/Projects/SDLtest/background.png" ); //打开字体信息 font = TTF_OpenFont( "D:/Users/lucy/Documents/Visual Studio 2008/Projects/SDLtest/lazy.ttf", 50); if( background == NULL ) { return false; } if( font == NULL ) { return false; } return true; }
void clean_up() { SDL_FreeSurface( background ); SDL_FreeSurface( message ); //不要忘记字体指针释放 TTF_CloseFont( font ); //使用完毕后使用TTF_Quit释放字体指针 TTF_Quit(); SDL_Quit(); }
int main(int argc,char *argv[]) { bool quit = false; if( init() == false ) { return 1; } if( load_files() == false ) { return 1; }
//渲染文字,先前定义的textcolor派上用场 message = TTF_RenderText_Solid( font, "Lucy is using SDL_ttf to render!",textColor); if( message == NULL ) { return 1; } apply_surface( 0, 0, background, screen ); apply_surface( 0, 150, message, screen ); if( SDL_Flip( screen ) == -1 ) { return 1; } //实现x屏幕就退出 while( quit == false ) { while( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) { quit = true; } } }
clean_up();//注意这个clean_up要包括对字体的回收
return 0; } 效果:
小结:
看完True Type的使用以后发现SDL的编写很规范,装载资源的时候必然都要经过初始化(XX_Init)->判空->装载资源(load)->资源的各种使用设置->从资源生成surface->surface的blit->指针释放(SDL_FreeXX)->资源销毁(XX_Quit)这几个过程。
TTF_Init:初始化字体的函数,如果初始化不成功就返回-1
TTF_OpenFont(字体位置,大小):装载字体的函数,返回一个TTF_Font指针
TTF_RenderText_Solid(字体指针,输出字符串,字体颜色(SDL_Color类型):设置字体的渲染方式,返回一个surface,SDL用其来渲染ASCII字符,其余的还有TTF_RenderUTF8_Solid用来渲染UTF8编码和TTF_RenderUNICODE_Solid用来渲染UCS2编码的字符串
TTF_CloseFont(字体指针):用来关闭由TTF_Open()打开的字体
TTF_Quit():关闭TTF的渲染