---
title: "opengl超级宝典代码学习2"
author: "sogotobj"
date: "2011-11-01T18:52:00Z"
tags: []
slug: "opengl-2"
draft: false
lastmod: "2011-11-09T20:00:34Z"
id: 1247786
url: "https://sogotobj.iteye.com/blog/1247786"
---

我们需要学习的第二个例子是在第二章的glrect例子。

// Called to draw scene

void RenderScene(void)

{

// Clear the window with current clearing color

glClear(GL\_COLOR\_BUFFER\_BIT);

// Set current drawing color to red

// R G B

glColor3f(1.0f, 0.0f, 0.0f);

// Draw a filled rectangle with current color

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

// Flush drawing commands

glFlush();

}

///////////////////////////////////////////////////////////

// Setup the rendering state

void SetupRC(void)

{

// Set clear color to blue

glClearColor(0.0f, 0.0f, 1.0f, 1.0f);

}

///////////////////////////////////////////////////////////

// Called by GLUT library when the window has chanaged size

void ChangeSize(int w, int h)

{

GLfloat aspectRatio;

// Prevent a divide by zero

if(h == 0)

h = 1;

// Set Viewport to window dimensions

glViewport(0, 0, w, h);

// Reset coordinate system

glMatrixMode(GL\_PROJECTION);

glLoadIdentity();

printf("w = %d::h = %d",w,h);

// Establish clipping volume (left, right, bottom, top, near, far)

aspectRatio = (GLfloat)w / (GLfloat)h;

if (w &lt;= h)

glOrtho (-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);

else

glOrtho (-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0);

glMatrixMode(GL\_MODELVIEW);

glLoadIdentity();

}

///////////////////////////////////////////////////////////

// Main program entry point

int main(int argc, char* argv\[])

{

glutInit(&argc, argv);

glutInitDisplayMode(GLUT\_SINGLE | GLUT\_RGB);

// glutInitWindowSize(800, 600);

glutCreateWindow("GLRect");

glutDisplayFunc(RenderScene);

glutReshapeFunc(ChangeSize);

SetupRC();

glutMainLoop();

return 0;

}

书中对代码解释的非常清楚。这个代码的关键在于当窗口的大小被改变的时候的回调函数ChangeSize的代码。这里h和w分别代表窗口新的高和宽，为了使得我们画的矩形保持正方形，代码如下：

if(w &lt;= h)

glOrtho(-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);

else

glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0);

这里可以看到opengl中实用的坐标系统是中心点坐标是（0,0）的普通笛卡儿坐标系统，和我们在屏幕上的坐标不同，屏幕上是原点在左上角，x是从左到右依次变大，不会出现负值，Y是从上到下依次变大，不会出现负值，但是opengl其实使用三维坐标系统，是符合右手法则的系统，原点在屏幕中心，X是从左到右变大，但是是从负值变到正值，Y是从下到上变大，从负值变成正值，Z垂直于屏幕，从里到外是从负值到正值的，这和大部分计算机的坐标系统不同。

我们使用函数glOrtho定义X和Y坐标的范围，这里X始终是从－100到正100，所以最后显示的正方形的长度始终是窗口的1／4,在高度上，我们设置为50个高，但是这个表示像素，它需要和glOrtho定义的Y坐标做比较来确定像素。

比如w=h的时候，是正方形，

w = 200;h=400的时候，那么矩形的长是50个像素,这个时候，整个opengl视图在Y上的坐标是－200到200,那么正好矩形的高占了整个视图的1／8,也正好是50个像素。

当w&gt;h的时候，以此类推。