// 利用ChangeSize函数在屏幕形状发生改变时重建viewport并且重新设置坐标系
#include <GL/glut.h>


#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480

void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat aspectRatio;

// 防止被0除
if(h == 0)

{
h = 1;
}

glViewport(0, 0, w, h);

// 重置坐标系统
glMatrixMode(GL_PROJECTION);

glLoadIdentity();

aspectRatio = (GLfloat) w / (GLfloat) h;
if(w <= h)
{
glOrtho(-100.0, 100.0, -100 / aspectRatio, 100 / aspectRatio, 1.0, -1.0);
}
else
{
glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100, 100, 1.0, -1.0);
}

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void SetupRC()
{
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
}

void RenderScene()
{
// 用当前的清除颜色清除窗口
glClear(GL_COLOR_BUFFER_BIT);

// 把绘图颜色设置为红色
glColor3f(1.0f, 0.0f, 0.0f);

glRectf(-25.0f, 25.0f, 25.0f, -25.0f);
glFlush();
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("GLUT Example!!!");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
SetupRC();

glutMainLoop();
return 0;
}

Copyright © 2024 无忧consume
Powered by .NET 9.0 on Kubernetes