# 学习OpenGL ES之透视和正交投影

### 获取示例代码

##### 正交投影矩阵

``````- (void)update {
[super update];
float varyingFactor = self.elapsedTime;

GLKMatrix4 rotateMatrix = GLKMatrix4MakeRotation(varyingFactor, 0, 1, 0);
//#define UsePerspective // 注释这行运行查看正交投影效果，解除注释运行查看透视投影效果
#ifdef UsePerspective
// 透视投影
float aspect = self.view.frame.size.width / self.view.frame.size.height;
GLKMatrix4 perspectiveMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(90), aspect, 0.1, 10.0);
GLKMatrix4 translateMatrix = GLKMatrix4MakeTranslation(0, 0, -1.6);
self.transformMatrix = GLKMatrix4Multiply(translateMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(perspectiveMatrix, self.transformMatrix);
#else
// 正交投影
float viewWidth = self.view.frame.size.width;
float viewHeight = self.view.frame.size.height;
GLKMatrix4 orthMatrix = GLKMatrix4MakeOrtho(-viewWidth/2, viewWidth/2, -viewHeight / 2, viewHeight/2, -10, 10);
GLKMatrix4 scaleMatrix = GLKMatrix4MakeScale(200, 200, 200);
self.transformMatrix = GLKMatrix4Multiply(scaleMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(orthMatrix, self.transformMatrix);
#endif

}
``````
``````- (void)drawTriangle {
static GLfloat triangleData[36] = {
-0.5,   0.5f,  0,   1,  0,  0, // x, y, z, r, g, b,每一行存储一个点的信息，位置和颜色
-0.5f,  -0.5f,  0,  0,  1,  0,
0.5f,   -0.5f,  0,  0,  0,  1,
0.5,    -0.5f, 0,   0,  0,  1,
0.5f,  0.5f,  0,    0,  1,  0,
-0.5f,   0.5f,  0,  1,  0,  0,
};
[self bindAttribs:triangleData];
glDrawArrays(GL_TRIANGLES, 0, 6);
}
``````

## 透视投影

`````` // 透视投影
float aspect = self.view.frame.size.width / self.view.frame.size.height;
GLKMatrix4 perspectiveMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(90), aspect, 0.1, 10.0);
GLKMatrix4 translateMatrix = GLKMatrix4MakeTranslation(0, 0, -1.6);
self.transformMatrix = GLKMatrix4Multiply(translateMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(perspectiveMatrix, self.transformMatrix);
``````

GLKit提供了`GLKMatrix4MakePerspective`方法便捷的生成透视投影矩阵。方法有4个参数`float fovyRadians, float aspect, float nearZ, float farZ``fovyRadians`表示视角。`aspect`表示屏幕宽高比，为了将所有轴的单位长度统一，所以需要知道屏幕宽高比多少。`nearZ`表示可视范围在Z轴的起点到原点(0,0,0)的距离，`farZ`表示可视范围在Z轴的终点到原点(0,0,0)的距离,`nearZ``farZ`始终为正。下面是透视投影的剖面示意图。

## 正交投影

`````` // 正交投影
float viewWidth = self.view.frame.size.width;
float viewHeight = self.view.frame.size.height;
GLKMatrix4 orthMatrix = GLKMatrix4MakeOrtho(-viewWidth/2, viewWidth/2, -viewHeight / 2, viewHeight/2, -10, 10);
GLKMatrix4 scaleMatrix = GLKMatrix4MakeScale(200, 200, 200);
self.transformMatrix = GLKMatrix4Multiply(scaleMatrix, rotateMatrix);
self.transformMatrix = GLKMatrix4Multiply(orthMatrix, self.transformMatrix);
``````

OpenGL ES