SDL在屏幕不工作之前制作图像

时间:2011-07-24 21:38:52

标签: c++ sdl

我正在搞乱SDL,我决定制作一个程序,打开图像作为主屏幕的背景,并使其动态化,因此不同大小的图像将导致不同大小的屏幕。问题是,我无法弄清楚为什么它不让我。我可以编译,但是当我尝试创建屏幕时程序会出错,因为背景图像由于某种未知原因而被取消。知道为什么吗?

该计划非常小:

#include <iostream>
#include "SDL/SDL.h"
#define bpp    32

int init(){
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
        return 1;
    // will init ttf later
    return 0;
}

SDL_Surface * open_image(std::string image_name){
    SDL_Surface * loaded_image = SDL_LoadBMP(image_name.c_str());
    if (loaded_image){
        SDL_Surface * optimized_image = SDL_DisplayFormat(loaded_image); // becomes NULL
        SDL_FreeSurface(loaded_image);
        return optimized_image;
    }
    return loaded_image;
}

int main(int argc, char * argv[]){
    if (init())
        return 1;

    SDL_Surface * background = open_image("hello.bmp");
    SDL_Surface * screen = SDL_SetVideoMode(background -> w, background -> h, bpp, SDL_SWSURFACE); // erroring here

    SDL_BlitSurface(background, NULL, screen, NULL);
    if (SDL_Flip(screen) == -1)
        return 1;   
    bool quit = false;
    SDL_Event event;
    while (!quit)
        while (SDL_PollEvent(&event))
            if (event.type == SDL_QUIT)
                quit = true;
    return 0;
}

我收到错误3,显然是访问不存在的值。在这种情况下,它是w和h来自背景,因为background是NULL,即使它不应该是

1 个答案:

答案 0 :(得分:2)

您无法在不调用SDL_SetVideoMode之前调用SDL_DisplayFormat。

我修复了你的代码:

    SDL_Surface * screen = SDL_SetVideoMode(512, 512, bpp, SDL_SWSURFACE);
    SDL_Surface * background = open_image("hello.bmp");
    screen = SDL_SetVideoMode(background -> w, background -> h, bpp, SDL_SWSURFACE);