2017-01-23 34 views
0

我無法嘗試使用下面的代碼加載我對這個PNG圖片:爲什麼我創建的表面不會加載?

#include <iostream> 
#include <SDL.h> 
#include<SDL_image.h> 
#include<string> 


SDL_Texture *LoadTexture(std::string filePath,SDL_Renderer*renderTarget) 
{ 
    SDL_Texture *texture=NULL; 
    SDL_Surface *surface= IMG_Load(filePath.c_str()); 
    if(surface==NULL) 
     std::cout<<"Error1"<<std::endl; 
    else 
    { 
     texture=SDL_CreateTextureFromSurface(renderTarget,surface); 
     if(texture==NULL) 
      std::cout<<"Error2"<<std::endl; 
    } 
    SDL_FreeSurface(surface); 
    return texture; 
} 

int main(int argc, char*argv[]) { 
//Initializing and loading variables 

    SDL_Window *window=NULL; 
    SDL_Renderer *renderTarget=NULL; 
    int currentTime=0; 
    int prevTime=0; 
    float delta=0.0f; 
    const Uint8 *keystate; 
    SDL_Rect camerRect={0,0,222,290}; 

    SDL_Init(SDL_INIT_VIDEO); 

    int data=10; 

    window=SDL_CreateWindow("SDL CodingMadeEeasY Series", SDL_WINDOWPOS_CENTERED, 
      SDL_WINDOWPOS_CENTERED,222,290, SDL_WINDOW_SHOWN); 
    renderTarget= SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); 

    SDL_Texture *texture=LoadTexture("spaceship_stock2.png",renderTarget); 


    bool isRunning=true; 
    SDL_Event ev; 

    while(isRunning) 
    { 
     prevTime=currentTime; 
     currentTime=SDL_GetTicks(); 
     delta=(currentTime-prevTime)/1000.0f; 
     while(SDL_PollEvent(&ev) != 0) 
     { 
      //Getting the events 
      if(ev.type==SDL_QUIT) 
       isRunning=false; 
     } 

     keystate=SDL_GetKeyboardState(NULL); 

     SDL_RenderClear(renderTarget); 
     SDL_RenderCopy(renderTarget,texture,&camerRect,NULL); 
     SDL_RenderPresent(renderTarget); 

    } 
     SDL_DestroyWindow(window); 
     SDL_DestroyRenderer(renderTarget); 
     SDL_DestroyTexture(texture); 

     texture=nullptr; 
     window=nullptr; 
     renderTarget=nullptr; 

     IMG_Quit(); 
     SDL_Quit(); 



return 0; 
} 

窗口輸出:正確大小的黑色窗口。

控制檯輸出:ERROR1

錯誤:沒有這個項目中與其他錯誤,由於未使用的變量只是警告。

編譯器無法找到我的PNG文件,即使我有調試文件夾中保存的spaceship_stock2.png的副本和保存在發佈文件夾中的副本。 Debug目前處於活動狀態,我正在使用Eclipse Helios。

我已經包含了庫標誌,並且爲庫和包含都設置了正確的路徑。

這是對a tutorial for scrolling backgrounds中CODING MADE EASY代碼的輕微修改。

+0

你的'IMG_Init()'調用和支持'IMG_INIT_PNG'的驗證在哪裏?你爲什麼不檢查'IMG_GetError()'來獲取更多的失敗信息?確認你的流程當前的工作目錄是你所假設的。 – genpfault

+0

謝謝,我通過在整體項目文件夾內但在調試和發佈文件夾外保存.png文件的副本來解決此問題。我通常通過項目瀏覽器複製和過去文件。你如何檢查工作目錄? –

+0

https://en.wikipedia.org/wiki/Working_directory – genpfault

回答

0

我能夠得到這個代碼來編譯和顯示圖像就好了。我改變的唯一的事情是<SDL.h>"SDL.h"<SDL_image.h>"SDL_image.h"

然後編譯,我在我的Linux系統上運行

c++ code_file_name.cpp `sdl2-config --cflags --libs` -lSDL2_image 

相關問題