SDL_LoadBMP()在引用曲面时显示黑色曲面

时间:2016-08-20 13:35:30

标签: c++ sdl

尝试将图像加载到SDL_Surface上。然而,表面总是黑色的,尽管bmp显然不是。

请注意

这是一个有效的SDL_Window并且创建一个表面指针是成功的,不成功的是加载" Kassadin.bmp"它位于Code :: Blocks项目文件夹中。它显示黑色表面。

在将此问题标记为重复之前,此特定问题的所有答案均未解决此问题。

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

  using namespace std;

  const int SCREEN_WIDTH = 700;
  const int SCREEN_HEIGHT = SCREEN_WIDTH / 12 * 9;

  //Create an SDL_Window pointer
  SDL_Window* window = NULL;

  //Create an SDL_Surface pointer
  SDL_Surface* surface = NULL;

  //SDL_Surface for an image
  SDL_Surface* imgSurface = NULL;

  bool init(){
  //try init SDL
  if(SDL_Init(SDL_INIT_VIDEO) < 0){
    cout << "Failed init SDL" << endl;
    return false;
  }else{

    //create window           title            x pos                    y  pos                    width         height         flags
    //This doesnt include a surface ie it will be a plain window
    window = SDL_CreateWindow("An SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

}

if(window == NULL){
    cout << "Failed creating SDL window" << endl;
    return false;
}else{
    // creates surface with an SDL_Window object
    surface = SDL_GetWindowSurface(window);
}
return true;
}

bool loadMedia(){
imgSurface = SDL_LoadBMP("Kassadin.bmp");

return true;
}

void close(){
//Sets the SDL_Window pointer to NULL again
SDL_DestroyWindow(window);

window = NULL;

SDL_FreeSurface (imgSurface);
imgSurface = NULL;

//quits
SDL_Quit();
}

int main(int argc, char* argv[]){

if(!init()){
    cout << "error init sdl" << endl;
}else{

    if(!loadMedia){
        cout << "Trouble loading media..." << endl;
    }else{

        SDL_BlitSurface(imgSurface, NULL, surface, NULL);

    }

}

//This is so it's not just a static window ie it can update
SDL_UpdateWindowSurface(window);

SDL_Delay(5000);

close();

return 0;
}

1 个答案:

答案 0 :(得分:0)

问题线是

if(!loadMedia){

这不是函数调用。它的作用是检查函数loadMedia的地址是否为NULL,由于链接器分配的函数地址(与在运行时手动分配的函数指针相反),因此总是为假。

正如您提到的代码块,我想您使用gcc来编译代码。如果只有你添加了至少-Wall标志(这是一个非常好的做法)编译器会警告你,你正在做一些非常看似错误的事情:

test2.cpp:70:9: warning: the address of ‘bool loadMedia()’ will always evaluate as ‘true’ [-Waddress]