首页 > 解决方案 > 如何在 SDL 中刷新屏幕(SDL_RenderClear 不起作用)?

问题描述

我正在尝试在 CodeBlocks 和 SDL 中制作一个简单的程序,每秒改变一个矩形的高度。到目前为止,我的代码是这样的:

'''

#include <SDL2/SDL.h>
#include <stdio.h>
#include <iostream>
#include <string>

int main(int argv, char** args)
{
    SDL_Window *p;
    SDL_Renderer *w;

    p = SDL_CreateWindow("Temp",SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,800,640,SDL_WINDOW_SHOWN);
    w = SDL_CreateRenderer(p, -1, SDL_RENDERER_ACCELERATED);

    SDL_SetRenderDrawColor(w,255,0,0,255);
    SDL_Rect Rect = {220,140,200,200};

//    int rectX = 220;
//    int rectY = 140;
//    int width = 200;
//    int height = 200;

    bool isRunning = true;
    SDL_Event event;

    int lastTime = 0;
    int currentTime = 0;

    while(isRunning)
    {
        // time stuff
        currentTime = SDL_GetTicks();
        int timeDifference = currentTime - lastTime;
        if(currentTime > lastTime + 1000)
        {
            lastTime = currentTime;
            height = 200;
        }
        // Check if window closes
        while ( SDL_PollEvent(&event))
        {
            if ( event.type == SDL_QUIT)
            {
            isRunning = false;
            }

            if ( event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE)
            {
            isRunning = false;
            }

        }
        // rectangle stuff
        SDL_SetRenderDrawColor(w,255,0,0,255);
        int newHeight = height + timeDifference / 4;
        Rect = {220,140,200,newHeight};

        SDL_RenderFillRect(w, &Rect);
        SDL_RenderPresent(w);
        SDL_Delay(10);

    }

    SDL_DestroyRenderer(w);
    SDL_DestroyWindow(p);
    SDL_Quit();
    return 0;
}

'''

每次它通过循环时,之前制作的矩形仍然存在。另外,我已经尝试过SDL_RenderClear,但是当它这样做时,整个屏幕都会变红。我该如何解决?我只是希望它每次都刷新。

另外,我知道之前的矩形仍然存在,因为我用有线矩形尝试过它,而且这样更明显。

标签: c++sdlcodeblockssdl-2

解决方案


推荐阅读