前几节我们了解到,SDL基本库只能加载普通的BMP图像,如果我们还想加载其它格式的图片,我们就需要用到SDL的扩展库,它可以帮助我们加载BMP, PNM, XPM, LBM, PCX, GIF, JPEG, TGA and PNG等格式图片。要下载SDL扩展帮助文档,点击此处!
使用扩展库之前,我们需要先从网上下载适合VS2010的库文件,点击此处,进入下载!如下图所示,下载该版本文件!
下载下来以后,同原来设置SDL基本库一样,我们设置好该扩展库的使用环境,复制dll文件至exe同目录下。
接着,我们修改上一节所写的load_image子函数,代码如下:
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;
//Loaded 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;
}
然后我们就可以加载包括BMP之内其它格式图片。在此,我准备了两幅图片,一幅test_png.png的png格式图片:
还有一幅background.bmp的bmp格式背景图片:
完整代码如下所示:
#include "SDL.h"
#include "SDL_image.h"
#include <string>
//The attributes of the screen
const int SCREEN_WIDTH = 600;
const int SCREEN_HEIGHT = 450;
const int SCREEN_BPP = 32;
//The surfaces that will be usede
SDL_Surface *message = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;
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;
//Loaded the image using SDL_image
// loadedImage = SDL_LoadBMP(filename.c_str());
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 *destination)
{
//Make a temporary rectangle to hold the offsets
SDL_Rect offset;
//Give the offset to the rectangle
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface(source,NULL,destination,&offset);
}
int main(int argc,char *argv[])
{
//Initialize all SDL_subsystems
if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return 1;
}
//Set up Screen
screen = SDL_SetVideoMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,SDL_SWSURFACE);
if(screen == NULL)
{
return 1;
}
//Set the window caption
SDL_WM_SetCaption("Hello World",NULL);
//Load Image
message = load_image("test_png.png");
background = load_image("background.bmp");
//Apply the background to the screen
apply_surface(0,0,background,screen);
//apply the message to the screen
apply_surface(105,78,message,screen);
//Update Screen
if(SDL_Flip(screen) == -1)
{
return 1;
}
//Wait 2 seconds
SDL_Delay(20000);
//Free the loaded image
SDL_FreeSurface(message);
SDL_FreeSurface(background);
//Quit SDL
SDL_Quit();
return 0;
}
最后效果如下: