更改SDL2窗口的背景?

时间:2015-05-21 15:11:21

标签: c++ sdl sdl-2

我可以创建一个SDL2窗口,但我不知道如何更改此窗口的背景颜色。

我的代码:

#include "SDL.h"

SDL_Window *window;

void main()
{
    window = SDL_CreateWindow("TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);

    SDL_Delay(3000);
}

如何将此窗口的背景颜色更改为黑色?

4 个答案:

答案 0 :(得分:12)

您应该使用SDL_SetRenderDrawColor设置绘图颜色,然后使用SDL_RenderClear

(代码直接来自SDL wiki

int main(int argc, char* argv[])
{
        SDL_Window* window;
        SDL_Renderer* renderer;

        // Initialize SDL.
        if (SDL_Init(SDL_INIT_VIDEO) < 0)
                return 1;

        // Create the window where we will draw.
        window = SDL_CreateWindow("SDL_RenderClear",
                        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                        512, 512,
                        0);

        // We must call SDL_CreateRenderer in order for draw calls to affect this window.
        renderer = SDL_CreateRenderer(window, -1, 0);

        // Select the color for drawing. It is set to red here.
        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);

        // Give us time to see the window.
        SDL_Delay(5000);

        // Always be sure to clean up
        SDL_Quit();
        return 0;
}

答案 1 :(得分:0)

如果您不使用SDL2渲染器,则可以执行以下操作:

只需拨打电话

SDL_GL_SwapWindow(window);

之后:

SDL_GL_MakeCurrent(window, context);

仅此而已!现在您有了黑屏。

答案 2 :(得分:0)

尝试一下:

SDL_Window *wind;
SDL_Surface *windSurface = NULL
void main()
{
    windSurface = SDL_GetWindowSurface(wind);  
   wind = SDL_CreateWindow("TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
    SDL_FillRect(windSurface, NULL, SDL_MapRGB(windSurface->format, 240, 200, 112));
        SDL_UpdateWindowSurface(wind);
    SDL_Delay(3000);
}

答案 3 :(得分:0)

#include <SDL2/SDL.h>
#include <iostream>
using namespace std;

int main(){
    int width=512, height=512;
    SDL_Window *window=SDL_CreateWindow("Window", SDL_WINDOWPOS_CENTERED, 
    SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE);

    if(window==NULL)
        cout << "There was an error while initializing the window" << endl << SDL_GetError << endl;

    SDL_Event event;
    bool running=true;

    while(running){
        while(SDL_PollEvent(&event)){
            if(event.type==SDL_QUIT){
                running=false;
                break;
            }
        }
        SDL_GetWindowSize(window, &width, &height);

        SDL_Surface *surface=SDL_GetWindowSurface(window);
        Uint32 skyblue=SDL_MapRGB(surface->format, 65,193,193);
        SDL_FillRect(surface, NULL, skyblue);
        SDL_UpdateWindowSurface(window);
    }

    SDL_DestroyWindow(window);
    SDL_Quit();
}