我使用SDL2创建了一个OpenGL窗口,但背景在黑色和黄色之间切换。
#include <SDL2/SDL.h>
#include <GL/glew.h>
#define SCREEN_WIDTH 500
#define SCREEN_HEIGHT 500
int main( int argc, char** argv )
{
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
SDL_Window* gWindow = SDL_CreateWindow(
"Title",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_OPENGL);
SDL_GL_CreateContext( gWindow );
glewExperimental = GL_TRUE;
glewInit();
glPointSize(3);
glClearColor(1,1,0,0);
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SetSwapInterval(1);
int quit=0;
SDL_Event event;
while( !quit )
{
while(SDL_PollEvent( &event ))
{
if( event.type == SDL_QUIT )
quit = 1;
}
SDL_GL_SwapWindow( gWindow );
}
SDL_DestroyWindow(gWindow);
return 0;
}
我希望背景为黄色,如glClearColor(1,1,0,0)所定义,在程序运行时不会闪烁。代码中有什么问题吗?
闪烁的原因是你正在使用双缓冲但不清除其中一个黄色缓冲区(即请注意你在代码中只调用一次glClear
)。
我建议你每帧都打电话给glClear
。要修复代码,可以将调用移到循环中,就在SDL_GL_SwapWindow
之前:
while( !quit )
{
while(SDL_PollEvent( &event ))
{
if( event.type == SDL_QUIT )
quit = 1;
}
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow( gWindow );
}