SDL教程3——优化图像加载和显示

上一节,我们学会了如何显示一个32位位图,现在是时候开始新学习了。思考,如果我们的图片不是32位,是24位的位图,我们该如何显示?如果我们想同时显示两幅图像,一幅前景图一幅背景图,该如何操作呢?

1、加载头文件

2、定义显示面参数

3、定义加载图片函数,主要是为了方便24位图像到32位图像的转换

4、定义显示图片函数,主要是为了方便在不同位置显示图片

5、mian主函数

程序中用到两幅位图,一幅backgroud.bmp,24位,600X450分辨率;一幅hello.bmp,24位,390X295分辨率,其他解释,请参考相关代码说明,下面附上源代码:

#include "SDL.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)
{
    //Temporary storage for the image that's loaded
    SDL_Surface *loadedImage = NULL;
 
    //The optimized image that will be used
    SDL_Surface *optimizedImage = NULL;
    
    //Load the image
    loadedImage = SDL_LoadBMP(filename.c_str());
 
    //If nothing went wrong in loading the image
    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("hello.bmp");
    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;
}

最后效果如图所示:

image

附录:

获取BMP图片小技巧:登录qq,然后打开百度图片,找到自己想要的一张图片,选择图片另存为,选择图片类型为BMP即可。如果图片太大,可用qq截图,然后同样保存为BMP图片即可!

posted @ 2013-02-21 10:32  阿Q程序员  阅读(977)  评论(0编辑  收藏  举报