01_SDL_在屏幕上顯示一張圖片

#include "SDL/SDL.h"
#include <string>

//屏幕屬性
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

//能被使用到的面
SDL_Surface *message = NULL;
SDL_Surface *background = NULL;
SDL_Surface *screen = NULL;

SDL_Surface *load_image( std::string filename )
{
    //臨時存儲圖像
    SDL_Surface* loadedImage = NULL;

    //存儲優化的圖像
    SDL_Surface* optimizedImage = NULL;

    //加載圖片
    loadedImage = SDL_LoadBMP( filename.c_str() );

    //若是在加載圖像時候沒有錯誤發生
    if( loadedImage != NULL )
    {
        //建立一個優化的圖像
        optimizedImage = SDL_DisplayFormat( loadedImage );

        //釋放舊圖像
        SDL_FreeSurface( loadedImage );
    }

    //返回優化圖像
    return optimizedImage;
}

void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
    //創建一個零時的矩陣設置顯示的座標
    SDL_Rect offset;

    //設置矩形的座標
    offset.x = x;
    offset.y = y;

    //顯示圖像
    SDL_BlitSurface( source, NULL, destination, &offset );
}

int main( int argc, char* args[] )
{
    //初始化全部SDL子系統
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return 1;
    }

    //創建一個屏幕
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //若是在設計屏幕的時候有錯誤
    if( screen == NULL )
    {
        return 1;
    }

    //設置窗口標題
    SDL_WM_SetCaption( "Hello World", NULL );

    //加載圖片
    message = load_image( "hello.bmp" );
    background = load_image( "background.bmp" );

    //將背景面應用到屏幕上
    apply_surface( 0, 0, background, screen );
    apply_surface( 320, 0, background, screen );
    apply_surface( 0, 240, background, screen );
    apply_surface( 320, 240, background, screen );

    //將加載圖片的面應用到屏幕上
    apply_surface( 180, 140, message, screen );

    //更新屏幕
    if( SDL_Flip( screen ) == -1 )
    {
        return 1;
    }

    //等待2秒
    SDL_Delay( 2000 );

    //釋放全部的面
    SDL_FreeSurface( message );
    SDL_FreeSurface( background );

    //退出SDL
    SDL_Quit();

    return 0;
}
相關文章
相關標籤/搜索