我正在制作一个简单的SDL应用程序,但出于某种原因,我的窗口将无法停留并且程序崩溃。这是代码:
bool CApp::onInit() {
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
return false;
display = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_HWSURFACE | SDL_DOUBLEBUF);
// Window pops up and disappears here.
if(display == nullptr) // display is NOT null
return false;
// Load the grid
Grid = CSurface::onLoad("Resources\\Images\\Grid.png");
if(Grid == nullptr)
return false; // Program crashes here due to onLoad returning nullptr.
// Load the X mark
X = CSurface::onLoad("Resources\\Images\\X.png");
if(X == nullptr)
return false;
// Load the O mark
O = CSurface::onLoad("Resources\\Images\\O.png");
if(X == nullptr)
return false;
return true;
}
阅读评论以查看程序错误的位置。
这是CSurface::onLoad()
函数。
SDL_Surface* CSurface::onLoad(char* File) {
SDL_Surface* surfTemp = nullptr; // Temporary Surface
SDL_Surface* surfReturn = nullptr; // Return Surface
surfTemp = SDL_LoadBMP(File); // This returns a nullptr for some reason
if(surfTemp == nullptr)
return nullptr; // This is the culprit for the program crashing.
// Optimize and free our surface.
surfReturn = SDL_DisplayFormat(surfTemp);
SDL_FreeSurface(surfTemp);
return surfReturn;
}
我不能为我的生活弄清楚为什么这不起作用。它以前工作过,但现在,它只是崩溃了!
答案 0 :(得分:3)
2个问题:
1)
// Load the X mark
X = CSurface::onLoad("Resources\\Images\\X.png");
if(X == nullptr)
return false;
// Load the O mark
O = CSurface::onLoad("Resources\\Images\\O.png");
if(X == nullptr)
return false;
第二项检查应该是评估O而不是X.
2)您正在使用SDL_LoadBMP
加载png图像。尝试使用SDL_Image扩展程序中的IMG_Load
。这就是它返回nullptr
的原因。 SDL_LoadBMP
期待一个BMP标题而它没有得到它。
答案 1 :(得分:1)
刚在我的机器上试过这个,觉得我发现了你的错误。
您正在尝试加载PNG文件时使用SDL_LoadBMP。 SDL_LoadBMP只能打开支持的Windows位图文件
如果您的图片必须采用BMP以外的格式, SDL_Image库将为您提供一组用于打开其他类型图像的功能。 http://www.libsdl.org/projects/SDL_image/