尝试blit图像时C ++ SDL2分段错误

时间:2015-10-12 18:36:03

标签: c++ segmentation-fault sdl

我有一个我不明白的段错误。 调试器说问题出在这一行:optimizedSurface = SDL_ConvertSurface(surface,windowSurface->format,1);

我想要使用的图像具有透明背景。 当我给它一个白色背景时,程序运行正常......

这是整个代码:

#include <SDL/SDL.h>
#include <stdio.h>
#include <iostream>

SDL_Surface * OptimizedSurface(std::string filePath, SDL_Surface * windowSurface){
    SDL_Surface * optimizedSurface = nullptr;
    SDL_Surface * surface = SDL_LoadBMP(filePath.c_str());
    optimizedSurface = SDL_ConvertSurface(surface,windowSurface->format,1);

    SDL_FreeSurface(surface);
    return optimizedSurface;
}

int main(int argc, char* args[]){
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window * window = nullptr;
    SDL_Surface * windowSurface = nullptr;
    SDL_Surface * currentImage = nullptr;
    SDL_Surface * player = nullptr;

    window = SDL_CreateWindow("SDL 2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800,600, SDL_WINDOW_SHOWN);
    windowSurface = SDL_GetWindowSurface(window);
    currentImage = OptimizedSurface("grass.bmp",windowSurface);
    player = OptimizedSurface("player.bmp",windowSurface);

    SDL_Rect drawingRect2;
    drawingRect2.x = 0;
    drawingRect2.y = 0;
    drawingRect2.w = 72;
    drawingRect2.h = 119;

    bool isRunning = true;
    SDL_Event ev;

    while(isRunning){
        while(SDL_PollEvent(&ev) != 0){
            if(ev.type == SDL_QUIT){
                isRunning = false;
            }else if(ev.type == SDL_KEYDOWN){
                if(ev.key.keysym.sym == SDLK_LEFT){
                    drawingRect2.x--;
                }
            }
        }
        SDL_BlitSurface(currentImage,NULL,windowSurface,NULL);
        SDL_BlitScaled(player,NULL,windowSurface,&drawingRect2);
        SDL_UpdateWindowSurface(window);
    }
    SDL_DestroyWindow(window);
    window = nullptr;
    SDL_FreeSurface(currentImage);
    currentImage = windowSurface = nullptr;
    SDL_Quit();

    return 0;
}

感谢任何帮助,谢谢。

0 个答案:

没有答案