SDL Guide 中文译版(二)[1]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 nightmare 的 blog

 

第二章 图像和视频

初始化sdl video显示

视频是最常用的部分,也是sdl最完整的子系统。下面的初始化过程是每个sdl程序都要做的,即使可能有些不同。

例2-1 初始化视频

    sdl_surface *screen;

    /* initialize the sdl library */
    if( sdl_init(sdl_init_video) < 0 ) {
        fprintf(stderr,
                "couldn't initialize sdl: %s\n", sdl_geterror());
        exit(1);
    }

    /* clean up on exit */
    atexit(sdl_quit);
    
    /*
     * initialize the display in a 640x480 8-bit palettized mode,
     * requesting a software surface
     */
    screen = sdl_setvideomode(640, 480, 8, sdl_swsurface);
    if ( screen == null ) {
        fprintf(stderr, "couldn't set 640x480x8 video mode: %s\n",
                        sdl_geterror());
        exit(1);
    }

初始化最佳视频模式

如果你希望某种色深(颜色数)但如果用户的显示器不支持也可以接受其他色深,使用加sdl_anyformat参数的sdl_setvideomode。您还可以用sdl_videomodeok来找到与请求模式最接近的模式。

例2-2 初始化最佳视频模式

    /* have a preference for 8-bit, but accept any depth */
    screen = sdl_setvideomode(640, 480, 8, sdl_swsurface|sdl_anyformat);
    if ( screen == null ) {
        fprintf(stderr, "couldn't set 640x480x8 video mode: %s\n",
                        sdl_geterror());
        exit(1);
    }
    printf("set 640x480 at %d bits-per-pixel mode\n",
           screen->format->bitsperpixel);

读取并显示bmp文件

当sdl已经初始化,视频模式已经选择,下面的函数将读取并显示指定的bmp文件。

例2-3 读取并显示bmp文件

void display_bmp(char *file_name)
{
    sdl_surface *image;

    /* load the bmp file into a surface */
    image = sdl_loadbmp(file_name);
    if (image == null) {
        fprintf(stderr, "couldn't load %s: %s\n", file_name, sdl_geterror());
        return;
    }

    /*
     * palettized screen modes will have a default palette (a standard
     * 8*8*4 colour cube), but if the image is palettized as well we can
     * use that palette for a nicer colour matching
     */
    if (image->format->palette && screen->format->palette) {
    sdl_setcolors(screen, image->format->palette->colors, 0,
                  image->format->palette->ncolors);
    }

    /* blit onto the screen surface */
    if(sdl_blitsurface(image, null, screen, null) < 0)
        fprintf(stderr, "blitsurface error: %s\n", sdl_geterror());

    sdl_updaterect(screen, 0, 0, image->w, image->h);

    /* free the allocated bmp surface */
    sdl_freesurface(image);
}

直接在显示上绘图

下面两个函数实现在图像平面的像素读写。它们被细心设计成可以用于所有色深。记住在使用前要先锁定图像平面,之后要解锁。

在像素值和其红、绿、蓝值间转换,使用sdl_getrgb()和sdl_maprgb()。

本文关键:sdl,game,multimedia,cross-platform
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top