【问题标题】:SDL Window Not AppearingSDL 窗口未出现
【发布时间】:2016-05-11 22:34:41
【问题描述】:

我正在尝试显示一个 SDL 窗口,但它似乎不起作用。程序将运行,显示窗口的功能将正常运行,但我的屏幕上没有任何显示。我在 Dock 中只有一个图标,表示程序没有响应。这是我的代码:

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

    MainComponent mainComponent;
    mainComponent.init();

    char myVar;

    cout << "Enter any key to quit...";
    cin >> myVar;

    return 0;
}

void MainComponent::init() {
    //Initialize SDL
    SDL_Init(SDL_INIT_EVERYTHING);

    window = SDL_CreateWindow("My Game Window", 100, 100, 100, 100, SDL_WINDOW_SHOWN);

    cout << screenWidth << " " << screenHeight << endl;

    if(window == nullptr) {
        cout << "Error could not create window" << SDL_GetError() << endl;
    }

    SDL_Delay(5000);

}

这是 Dock 上图标的屏幕截图https://www.dropbox.com/s/vc01iqp0z07zs25/Screenshot%202016-02-02%2017.26.44.png?dl=0 如果我做错了什么,请告诉我,谢谢!

【问题讨论】:

    标签: c++ sdl


    【解决方案1】:

    SDL_Renderer 应该被初始化来处理渲染。这在What is a SDL renderer? 有详细解释。

    这是上面修改后的代码,带有初始化的渲染器;

    #include <SDL2/SDL.h>
    #include <iostream>
    
    using namespace std;
    
    class MainComponent
    {
     public:
        void init();
        ~MainComponent();
    
     private:
        SDL_Window *window;
        SDL_Renderer* renderer;
    };
    
    MainComponent::~MainComponent()
    {
      SDL_DestroyRenderer(renderer);
      SDL_DestroyWindow(window);
    }
    
    void MainComponent::init() {
        //Initialize SDL
        SDL_Init(SDL_INIT_EVERYTHING);
    
        int screenWidth = 400;
        int screenHeight = 300;
    
        window = SDL_CreateWindow("My Game Window", 100, 100, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
        renderer = SDL_CreateRenderer(window, -1, 0);
    
        cout << screenWidth << " " << screenHeight << endl;
    
        if(window == nullptr) {
            cout << "Error could not create window" << SDL_GetError() << endl;
        }
    
        //change the background color
        SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    
        // Clear the entire screen to our selected color.
        SDL_RenderClear(renderer);
    
        // Up until now everything was drawn behind the scenes.
        // This will show the new, red contents of the window.
        SDL_RenderPresent(renderer);
    
    
        SDL_Delay(5000);
    
    }
    
    
    int main(int argc, const char * argv[]) {
    
        MainComponent mainComponent;
        mainComponent.init();
    
        char myVar;
    
        cout << "Enter any key to quit...";
        cin >> myVar;
    
        SDL_Quit();
        return 0;
    }
    

    这应该可以正确编译和运行。 希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多