OpenGL中的变换:
平移:glTranslate3f(dx,dy,dz);
旋转:glRotate3f(angle, x, y, z);
缩放:glScale3f(sx, sy, sz);
练习内容:
- 在窗口中绘制一个圆形和矩形。 ;
- 再绘制一遍相同的圆和矩形,并作恰当的变换,使它们组合成一辆卡通汽车的形状。整个图形都显示在视图窗口内;
#include <windows.h>
#include <gl/glut.h>
#include "math.h"
int n = 3600; //圆绘制次数
float PI = 3.1415926f;
float R = 0.8f; //半径
void init(void) {
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-5.0, 5.0, -5.0, 5.0); //设置显示的范围是X:-5.0~5.0, Y:-5.0~5.0
glMatrixMode(GL_MODELVIEW); //设置当前操作的矩阵为“模型视图矩阵”
}
void drawSquare(void)
{
glBegin(GL_POLYGON); //顶点指定需要按逆时针方向
glVertex2f(-1.0f,-1.0f); //左下点
glVertex2f(1.0f,-1.0f); //右下点
glVertex2f(1.0f,1.0f); //右上点
glVertex2f(-1.0f,1.0f); //左上点
glEnd();
}
void drawCircle(void)
{
//画圆
glClearColor(0, 0, 0, 0);
glColor4f(0, 0, 1, 0);
glBegin(GL_POLYGON);
for (int i = 0; i < n; i++)
{
glVertex2f(R * cos(2 * PI * i / n), R * sin(2 * PI * i / n)); //定义顶点
}
glEnd();
}
void myDraw(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glTranslatef(0.0f,0.0f,0.0f);
glScalef(2.0,0.8,1.0);
glColor3f(1.0,0.0,0.0);
drawSquare();
glPopMatrix(); //下矩形
glPushMatrix();
glTranslatef(0.8f, 1.2f, 1.0f);
glScalef(0.8, 0.4, 0.8);
glColor3f(0.0, 1.0, 0.0);
drawSquare();
glPopMatrix(); //上矩形
glPushMatrix();
glTranslatef(-1.0f, -0.8f, 0.0f);
glScalef(0.6, 0.6, 1.0);
glColor3f(0.0, 0.0, 1.0);
drawCircle();
glPopMatrix(); //左圆
glPushMatrix();
glTranslatef(1.0f, -0.8f, 0.0f);
glScalef(0.6, 0.6, 1.0);
glColor3f(0.0, 0.0, 1.0);
drawCircle();
glPopMatrix(); //右圆
glFlush();
}
void main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(0,0);
glutInitWindowSize(600,600);
glutCreateWindow("绘制小汽车");
init();
glutDisplayFunc(myDraw);
glutMainLoop();
}