gpt4 book ai didi

c++ - 不正确的随机彩色矩形

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:03:31 24 4
gpt4 key购买 nike

我想在 GL_POLYGON 中显示随机颜色。

但是颜色只在最小化和最大化时改变。它在最大化时选择不同的颜色,在最小化时选择不同的颜色。但是只要我继续最小化和最大化它就会随机化颜色

#include <GL/gl.h>
#include <GL/glut.h>
#include <cstdlib>

void display( void )
{
glClear( GL_COLOR_BUFFER_BIT );
glBegin( GL_POLYGON );
for( int i = 0; i < 255; i++ )
{
glColor3ub( rand(), rand(), rand() );
}
glVertex3f( 0.25, 0.25, 0.0 );
glVertex3f( 0.75, 0.25, 0.0 );
glVertex3f( 0.75, 0.75, 0.0 );
glVertex3f( 0.25, 0.75, 0.0 );
glEnd();

glColor3f( 0.0, 0.0, 0.0 );
glRectf( 0.45, 0.25, 0.55, 0.05 );
glRectf( 0.35, 0.08, 0.65, 0.02 );

glFlush();
}

void init( void )
{
glClearColor( 1.0, 1.0, 1.0, 1.0 );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, 1.0, 0.0, 1.0, -1.0, 1.0 );
}

int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize( 250, 250 );
glutInitWindowPosition( 100, 100 );
glutCreateWindow( "Assignment" );
init();
glutDisplayFunc( display );
glutMainLoop();
return 0;
}

最佳答案

glutDisplayFunc()仅在操作系统需要重新绘制窗口时调用您的回调。如果你想要更多的定期调用,你需要通过 glutPostRedisplay() 自己触发它们:

... When GLUT determines that the normal plane for the window needs to be redisplayed, the display callback for the window is called. ...

...

GLUT determines when the display callback should be triggered based on the window's redisplay state. The redisplay state for a window can be either set explicitly by calling glutPostRedisplay or implicitly as the result of window damage reported by the window system. Multiple posted redisplays for a window are coalesced by GLUT to minimize the number of display callbacks called.

我喜欢使用 glutTimerFunc() 定期调用 glutPostRedisplay():

#include <GL/glut.h>
#include <cstdlib>

void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}

void display()
{
glClearColor( 0.2, 0.2, 0.2, 1 );
glClear( GL_COLOR_BUFFER_BIT );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();

glBegin( GL_POLYGON );
glColor3ub( rand(), rand(), rand() );
glVertex3f( 0.25, 0.25, 0.0 );
glVertex3f( 0.75, 0.25, 0.0 );
glVertex3f( 0.75, 0.75, 0.0 );
glVertex3f( 0.25, 0.75, 0.0 );
glEnd();

glColor3f( 0.0, 0.0, 0.0 );
glRectf( 0.45, 0.25, 0.55, 0.05 );
glRectf( 0.35, 0.08, 0.65, 0.02 );

glutSwapBuffers();
}

int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 250, 250 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}

关于c++ - 不正确的随机彩色矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com