如何使用SDL2在C ++中将框渲染到屏幕上?

时间:2019-01-04 00:34:45

标签: c++ sdl-2

我正在尝试弄清楚C ++中的SDL2库,并且似乎无法正确配置代码以简单地在屏幕上绘制矩形。我应该怎么做?

#include <SDL.h>
bool success = true;  //success flag for functions, etc
int ScreenWidth = 640;  //screen width and height for SDL window
int ScreenHeight = 480; //
int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
    SDL_Window* window = SDL_CreateWindow( "Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor( renderer, 0xFF, 0xFF, 0xFF, 0xFF);  

    bool quit = false;
    SDL_Event event;
    while (!quit)
    {
        SDL_RenderClear(renderer);
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
                quit = true;
        }
        SDL_Rect box;
        box.w = 30;
        box.h = 30;
        box.x = 50;
        box.y = 50;
        SDL_SetRenderDrawColor(renderer, 0xFF,0x00,0x00,0xFF);
        SDL_RenderFillRect(renderer, &box);
        SDL_RenderPresent(renderer);    
    }
    return 0; //because main is an int task
}

编辑:这是完整文件。

我希望它在屏幕上绘制一个红色矩形,但是窗口是完全红色的(具有正确的大小,名称等,可以正确退出)。

3 个答案:

答案 0 :(得分:2)

您必须在所有渲染调用之后调用SDL_RenderPresent。在这种情况下,SDL_RenderFillRect(...)

之后

SDL_RenderClear用于渲染循环的开始,以清除缓冲区。

Example from SDL2's Wiki

答案 1 :(得分:0)

SDL_SetRenderDrawColor()影响SDL_RenderFillRect() SDL_RenderClear()

绘制红色正方形后,您需要在下一个SDL_RenderClear()调用之前将颜色重新设置为白色:

#include <SDL2/SDL.h>

int main( int argc, char** argv )
{
    SDL_Init( SDL_INIT_EVERYTHING );
    SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" );
    SDL_Window* window = SDL_CreateWindow( "Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN );
    SDL_Renderer* renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );

    bool running = true;
    while( running )
    {
        SDL_Event ev;
        while( SDL_PollEvent( &ev ) )
        {
            if( SDL_QUIT == ev.type )
            {
                running = false;
                break;
            }
        }

        SDL_SetRenderDrawColor( renderer, 0xFF, 0xFF, 0xFF, 0xFF );
        SDL_RenderClear( renderer );

        SDL_Rect box;
        box.w = 30;
        box.h = 30;
        box.x = 50;
        box.y = 50;
        SDL_SetRenderDrawColor( renderer, 0xFF, 0x00, 0x00, 0xFF );
        SDL_RenderFillRect( renderer, &box );

        SDL_RenderPresent( renderer );
    }

    return 0;
}

答案 2 :(得分:0)

我知道了!

我需要放置SDL_SetRenderDrawColor(renderer,0xFF,0xFF,0xFF,0xFF);在循环内部,因此它将渲染器重置为每个刻度为白色。我刚开始就将其设置为白色,因此SDL_RenderClear使用当前绘制颜色(红色)填充了窗口。感谢TinfoilPancakes和genpfault对我的帮助!