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图片即可!

转载于:https://www.cnblogs.com/MrTan/archive/2013/02/21/2920117.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值